Python Pillow:在发送到第 3 方服务器之前使图像渐进

Python Pillow: Make image progressive before sending to 3rd party server

我有一张图片,我正在使用 Django Forms 上传,它在变量中可用 InMemoryFile 我想做的是让它渐进。

使图像渐进的代码

img = Image.open(source)
img.save(destination, "JPEG", quality=80, optimize=True, progressive=True)

Forms.py

my_file = pic.pic_url.file
photo = uploader.upload_picture_to_album(title=title, file_obj=my_file)

问题是,我必须保存文件以防我想让它渐进,然后再次打开它以将其发送到服务器。 (让它进步似乎是多余的动作)

我只是想知道是否有一种渐进式图像,它不会将图像物理保存在磁盘上,而是保存在内存中,我可以使用现有代码上传它吗?

想法

正在寻找类似的东西。

    my_file=pic.pic_url.file
    progressive_file = (my_file)
    photo = picasa_api.upload_picture_to_album(title=title, file_obj=progressive_file)

如果您不想将中间文件保存到磁盘,则可以将其保存到 StringIOPIL.open()PIL.save() 都接受 file-like 对象和文件名。

img = Image.open(source)
progressive_img = StringIO()
img.save(progressive_img, "JPEG", quality=80, optimize=True, progressive=True)
photo = uploader.upload_picture_to_album(title=title, file_obj=progressive_img)

上传者需要支持使用 StringIO 但希望如此。

可能可以使用合适的协同程序直接从 save() 流式传输结果,但这需要多做一些工作。