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

Sem*_*emo 2 python python-imaging-library

我想将 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)
Run Code Online (Sandbox Code Playgroud)

错误信息如下:

TypeError: a bytes-like object is required, not 'PhotoImage'
Run Code Online (Sandbox Code Playgroud)

我通常会找到将 ImageTk 对象转换为 PIL 对象的方法,但反之则不然。从文档中我也无法得到任何提示。

Har*_* K. 5

您可以首先使用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)
Run Code Online (Sandbox Code Playgroud)