Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 687
A.J. Avatar asked Nov 09 '22 08:11

A.J.


1 Answers

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.

like image 157
dhke Avatar answered Nov 14 '22 21:11

dhke