Tkinter 以错误的比例保存画布 [英] Tkinter saving canvas at wrong scale

查看:27
本文介绍了Tkinter 以错误的比例保存画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用 tkinter 编写一个绘图程序,我的一个函数保存了最终的画布输出(我的图像在画布上的坐标 0,0 处渲染).我将画布作为 postscript 文件保存到内存中,并使用 PIL 将 postscript 以 PNG 格式保存到磁盘(PIL 在保存 postscript 文件时使用 ghostscript).但是,画布始终保存为原始大小的 60.15%.我想将图像保存为原始大小的 100%,但我不知道如何在我的代码中执行此操作.

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.

这是我的代码如下:

 """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):

推荐答案

原来 postscript 是一种矢量化的图像格式,图像在光栅化之前需要进行缩放.您的矢量比例可能与我的不同(我的为 0.60):如果此代码中的 DPI 比例因子不适合您,您可以在封装的 postscript 文件中查看比例因子

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

开放EPS代码取自这篇文章:python乌龟画布转位图时如何保持画布大小

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

这篇关于Tkinter 以错误的比例保存画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆