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

标签 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)

错误信息如下:

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)

关于python - 如何将 PIL.ImageTk.PhotoImage 保存为 jpg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45440746/

相关文章:

python - 将 bool numpy 数组转换为枕头图像

python - 如何在 Pillow Image.quantize 中使用 kmeans 参数?

python - 算法:用枕头创建六边形

python - 检测反射 DLL 注入(inject)

python - 如何使用 doctest 进行日志记录?

python - AttributeError : 'str' object has no attribute 'findAll' , 使用 BeautifulSoup 从 Youtube 抓取数据时无输出

python - 关于 PIL 错误 -- IOError : decoder zip not available

python - 如何处理ValueError : Classification metrics can't handle a mix of multilabel-indicator and multiclass targets error

python - 如何在 mongoengine 中仅包含选定的嵌入文档?

java - 将 XML 位图数据转换为图像