繁体   English   中英

如何将 PIL.ImageTk.PhotoImage 保存为 jpg

[英]How to save PIL.ImageTk.PhotoImage as jpg

我想将 PIL.ImageTk.PhotoImage 保存到文件中。 我的方法是创建一个“打开”的文件并调用“写入”方法,但它不起作用,因为我不知道如何从对象中获取字节数组。

def store_temp_image(data, image):
    new_file_name = data.number + ".jpg"
    with open(os.path.join("/tmp/myapp", new_file_name), mode='wb+') as output:
        output.write(image)

错误信息如下:

TypeError: a bytes-like object is required, not 'PhotoImage'

我通常会找到将 ImageTk 对象转换为 PIL 对象的方法,但反过来不行。 从文档中我也没有得到任何提示。

您可以先使用ImageTk.getimage()函数(向下滚动,接近尾声)获取 PIL Image,然后使用其 save() 方法:

def store_temp_image(data, imagetk):
    # do sanity/validation checks here, if need be
    new_file_name = data.number + ".jpg"
    imgpil = ImageTk.getimage( imagetk )
    imgpil.save( os.path.join("/tmp/myapp", new_file_name), "JPEG" )
    imgpil.close()    # just in case (not sure if save() also closes imgpil)

看看这个...

http://pillow.readthedocs.io/en/3.1.x/reference/ImageTk.html#PIL.ImageTk.PhotoImage

从那里你可以得到包含的 Image 对象。 其中有一个save(...)方法可以完成您期望的工作。

http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.save

因此,这个(未经测试的)代码应该可以完成这项工作:

def store_temp_image(data, image):
    new_file_name = data.number + ".jpg"
    new_file_path = os.path.join('/tmp/myapp', new_file_name)
    image.image.save(new_file_path)

希望这有帮助!

查看ImageTk 模块的源代码,您可以看到它实际上创建了一个 tkinter.PhotoImage 对象并将其存储为 __photo。

self.__photo = tkinter.PhotoImage(**kw)

此属性可作为_PhotoImage__photo访问(由于前导__它的名称已被破坏)。
然后,要保存图像, 您可以执行以下操作

image._PhotoImage__photo.write("/tmp/myapp"+new_file_name)

请注意,这仅支持非常有限的文件格式选择。 它适用于 png 文件、gif 文件和 ppm 文件,但不适用于 jpg 文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM