如何将PIL.ImageTk.PhotoImage保存为jpg [英] How to save PIL.ImageTk.PhotoImage as jpg

查看:1079
本文介绍了如何将PIL.ImageTk.PhotoImage保存为jpg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to save a PIL.ImageTk.PhotoImage into a file. My approach is to create a file "with open" and call the "write" method, but it wont't work, because I don't know how to get the byte-array from the object.

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对象的方法,但反之则不行.从文档中我也找不到任何提示.

I usually find approaches to convert ImageTk Objects into PIL objects, but not the other way round. From the docs I couldn't get any hints neither.

推荐答案

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

Looking at the source code for the ImageTk module, you can see that it actually creates a tkinter.PhotoImage object and stores it as __photo.

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

此属性可以作为_PhotoImage__photo访问(由于前导__其名称已被修改).
然后,要保存图像,您可以做到:

this attribute is accessible as _PhotoImage__photo (because of the leading __, it's name has been mangled).
Then, to save your image, you can do:

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

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

Be warned that this only supports a very limited choice of file formats. It worked for me with png files, gif files and ppm files, but not with jpg files.

这篇关于如何将PIL.ImageTk.PhotoImage保存为jpg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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