1

I have been writing a paint program in tkinter, and one of my functions saves the final canvas output (my image is rendererd on the canvas at coord 0,0). I save the canvas to memory as a postscript file and use PIL to save the postscript to disk as a PNG (PIL uses ghostscript when saving a postscript file). The canvas is always saved at 60.15% of it's original size, however. I would like to save the image as 100% of it's original size, though i can't figure out how to do this in my code.

Here is my code below:

 """my image is 256 x 256"""
ps = self.canvas_image.canvas.postscript(colormode='color',  x = 0, y = 0, 
            height = 256, width = 256)
im = Image.open(BytesIO(ps.encode('utf-8')))
im.save(filepath, "PNG")

And here are my images (top is original image, bottom is saved image):

Original image

enter image description here

1 Answers1

4

Turns out that postscript is a vectorized image format, and the image needs to be scaled before being rasterized. Your vector scale may be different than mine (mine was 0.60): you can view the scale factor in an encapsulated postscript file if the DPI scale factors in this code don't work for you

The open EPS code was taken from this post: how to maintain canvas size when converting python turtle canvas to bitmap

I used this code snippet to solve my problem:

ps = self.canvas_image.canvas.postscript(colormode='color', x = 0, y = 0,  height = 256, width = 256)                                                 

""" canvas postscripts seem to be saved at 0.60 scale, so we need to increase the default dpi (72) by 60 percent """
im = open_eps(ps, dpi=119.5)
#im = Image.open('test.ps')
im.save(filepath, dpi=(119.5, 119.5))

def open_eps(ps, dpi=300.0):
    img = Image.open(BytesIO(ps.encode('utf-8')))
    original = [float(d) for d in img.size]
    scale = dpi/72.0            
    if dpi is not 0:
        img.load(scale = math.ceil(scale))
    if scale != 1:
        img.thumbnail([round(scale * d) for d in original], Image.ANTIALIAS)
    return img