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

A.J*_*.J. 5 python django python-imaging-library pillow

我有一个使用 Django Forms 上传的图像,它在变量中可用,因为InMemoryFile我想要做的是使其渐进式。

使图像渐进式的代码

img = Image.open(source)
img.save(destination, "JPEG", quality=80, optimize=True, progressive=True)
Run Code Online (Sandbox Code Playgroud)

表单.py

my_file = pic.pic_url.file
photo = uploader.upload_picture_to_album(title=title, file_obj=my_file)
Run Code Online (Sandbox Code Playgroud)

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

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

主意

寻找类似的东西。

    my_file=pic.pic_url.file
    progressive_file = (my_file)
    photo = picasa_api.upload_picture_to_album(title=title, file_obj=progressive_file)
Run Code Online (Sandbox Code Playgroud)

dhk*_*hke 2

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

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

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

可能可以save()使用合适的协程直接传输结果,但这需要更多的工作。