Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving in memory file object with pillow

In my django project I have a inmemoryuploadedfile, I then open this with Pillow, rotate it, and save it back to itself. The last step doesn't actually work however. When I save it to a file the correct(rotated) image is saved. How can I save back to the file object instead of an actual file?

    image = request.FILES['file']
    img = Image.open(image)
    img = img.rotate(90)
    img.save("sample.jpeg", "jpeg") #this is correct
    img.save(image, "jpeg") #this does not change the actual in memory image
like image 690
Igglyboo Avatar asked Apr 28 '14 18:04

Igglyboo


1 Answers

You have to reset the the stream position of the underlying StreamIO-object that holds your uploaded file. Otherwise Image.save() will only append to the end of the stream.

You might also need to reset stream position before trying to read the file from memory again.

image = request.FILES['file']
img = Image.open(image)
img = img.rotate(90)
image.seek(0)
img.save(image, "jpeg")
image.seek(0)
image.read()

Note that UploadedFile (base class of InMemoryUploadedFile) keeps track of the file size, and if you are changing the underlying file object, code depending on the InMemoryUploadedFile.size may get confused.

like image 96
Mathias Bois Avatar answered Oct 16 '22 21:10

Mathias Bois