How to save PIL.ImageTk.PhotoImage as jpg

2019-08-04 06:36发布

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)

The error message is as follows:

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

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.

1条回答
叼着烟拽天下
2楼-- · 2019-08-04 07:03

Have a look at this...

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

From there you can get the included Image object. Which has a save(...) method that does the job you're expecting.

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

Thus this (untested) code should do the job :

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)

Hope this helped!

查看更多
登录 后发表回答