Save turtle output as jpeg

这一生的挚爱 提交于 2019-11-30 21:22:29

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!