Skip to content Skip to sidebar Skip to footer

How To Convert A Python Tkinter Canvas Postscript File To An Image File Readable By The PIL?

So I have created a function in my program that allows the user to save whatever he/she draws on the Turtle canvas as a Postscript file with his/her own name. However, there have b

Solution 1:

If you don't supply the file parameter in the call to cnv.postscript, then a cnv.postscript returns the PostScript as a (unicode) string. You can then convert the unicode to bytes and feed that to io.BytesIO and feed that to Image.open. Image.open can accept as its first argument any file-like object that implements read, seek and tell methods.

import io
def savefirst():
    cnv = getscreen().getcanvas() 
    global hen
    ps = cnv.postscript(colormode = 'color')
    hen = filedialog.asksaveasfilename(defaultextension = '.jpg')
    im = Image.open(io.BytesIO(ps.encode('utf-8')))
    im.save(hen + '.jpg')

For example, borrowing heavily from A. Rodas' code,

import Tkinter as tk
import subprocess
import os
import io
from PIL import Image

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.line_start = None
        self.canvas = tk.Canvas(self, width=300, height=300, bg="white")
        self.canvas.bind("<Button-1>", lambda e: self.draw(e.x, e.y))
        self.button = tk.Button(self, text="save",
                                command=self.save)
        self.canvas.pack()
        self.button.pack(pady=10)

    def draw(self, x, y):
        if self.line_start:
            x_origin, y_origin = self.line_start
            self.canvas.create_line(x_origin, y_origin, x, y)
        self.line_start = x, y

    def save(self):
        ps = self.canvas.postscript(colormode='color')
        img = Image.open(io.BytesIO(ps.encode('utf-8')))
        img.save('/tmp/test.jpg')

app = App()
app.mainloop()

Solution 2:

Adding to unutbu's answer, you can also write the data again to a BytesIO object, but you have to seek to the beginning of the buffer after doing so. Here's a flask example that displays the image in browser:

@app.route('/image.png', methods=['GET'])
def image():
    """Return png of current canvas"""
    ps = tkapp.canvas.postscript(colormode='color')
    out = BytesIO()
    Image.open(BytesIO(ps.encode('utf-8'))).save(out, format="PNG")
    out.seek(0)
    return send_file(out, mimetype='image/png')

Post a Comment for "How To Convert A Python Tkinter Canvas Postscript File To An Image File Readable By The PIL?"