Save turtle output as jpeg

Lillz picture Lillz · Jul 31, 2014 · Viewed 8.4k times · Source

I have a fractal image creator. It creates a random fractal tree like thing. When done, it prompts the user to save the tree. I have it saving as a .svg right now and that works BUT I want it to save to a more convenient file type, like jpeg. Any ideas? Code:

import turtle
import random
from sys import exit
from time import clock
import canvasvg
turtle.colormode(255)
red = 125
green = 70
blue = 38        
pen = 10
def saveImg():
    print("Done.")
    save = input("Would you like to save this tree? Y/N \n")
    if save.upper() == "Y":
        t.hideturtle()
        name = input("What would you like to name it? \n")
        nameSav = name + ".svg"
        ts = turtle.getscreen().getcanvas()
        canvasvg.saveall(nameSav, ts)
    elif save.upper() == "N":
        def runChk():
            runAgain = input("Would you like to run again? Y/N (N will exit)")
            if runAgain.upper() == "Y":
                print("Running")
                main()
            elif runAgain.upper() == "N":
                print("Exiting...")
                exit()
            else:
                print("Invalid response.")
                runChk()
        runChk()
    else:
        print("Invalid response.")
        saveImg()

def tree(branchLen, t, red, green, blue, pen):
    time = str(round(clock()))
    print("Drawing... " + time)
    if branchLen > 3:
        pen = pen*0.8
        t.pensize(pen)
        if (red > 10 and green < 140):
            red = red - 15
            green = green + 8
    if branchLen > 5:
        angle = random.randrange(18, 55)
        angleTwo = 0.5*angle
        sub = random.randrange(1,16)
        t.color(red, green, blue)
        t.forward(branchLen)
        t.right(angleTwo)
        tree(branchLen-sub,t, red, green, blue, pen)
        t.left(angle)
        tree(branchLen-sub, t, red, green, blue, pen)
        t.right(angleTwo)
        t.backward(branchLen)

def main():
    t = turtle.Turtle()
    myWin = turtle.Screen()
    t.speed(0)
    t.hideturtle()
    t.left(90)
    t.up()
    t.backward(100)
    t.down()
    print("Please wait while I draw...")
    tree(random.randrange(60,95),t,red,green,blue, pen)
    saveImg()
main()

Answer

mhawke picture mhawke · Jul 31, 2014

Does it have to be a JPEG? Would PNG suffice?

If so you can convert from SVG to PNG using cairosvg. Unfortunately canvasvg.saveall() only allows you to pass it a file name into which it will write the SVG, so you will need to use a temporary file for the SVG and then convert that temp file to PNG using cairosvg.svg2png(). So something like this should do the job:

import os
import shutil
import tempfile

import canvasvg

name = raw_input("What would you like to name it? \n")
nameSav = name + ".png"
tmpdir = tempfile.mkdtemp()  # create a temporary directory
tmpfile = os.path.join(tmpdir, 'tmp.svg')  # name of file to save SVG to
ts = turtle.getscreen().getcanvas()
canvasvg.saveall(tmpfile, ts)
with open(tmpfile) as svg_input, open(nameSav, 'wb') as png_output:
    cairosvg.svg2png(bytestring=svg_input.read(), write_to=png_output)
shutil.rmtree(tmpdir)  # clean up temp file(s)

If you liked, you could write your own saveall() function based on canvasvg.saveall() (it's quite small) that accepts a file-like object instead of a file name, and writes to that object. Then you can pass in a StringIO object and not have to bother with the temporary file. Or your saveall() could just return the SVG data as a byte string.