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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With