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

我与影子孤独终老i 提交于 2019-12-06 05:38:17

问题


I have an image that I am uploading using Django Forms, and its available in the variable as InMemoryFile What I want to do is to make it progressive.

Code to make an image a progressive

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)

The issue is, I have to save the file in case I want to make it progressive, and open it again to send it to the server. (It seems a redundant actions to make it progressive)

I just want to know if there is anyway to make an image progressive which does not save the image physically on disk but in memory, which I can use the existing code to upload it?

Idea

Looking for something similar.

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

回答1:


If all you want is not saving the intermediate file to disk, you can save it to a StringIO. Both PIL.open() and PIL.save() accept file-like objects as well as filenames.

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)

The uploader needs to support working with the StringIO but that is hopefully the case.

It's probably possible to directly stream the result from save() using suitable coroutines, but that is a little more work.



来源:https://stackoverflow.com/questions/31759712/python-pillow-make-image-progressive-before-sending-to-3rd-party-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!