'Error Rotating a django InMemoryUploadedFile image based on exif data
I am trying to rotate an image based on the image's exif data. The image is uploaded using the django admin request.FILES. If the file is large, and is uploaded as an TemporaryUploadedFile, and I can rotate the image correctly. However, I am having an issue when the image is smaller and uploaded as an InMemoryUploadedFile.
When the image is an InMemoryUploadedFile, I can rotate the image based on the exif data and save it to disk. The image on disk is rotated correctly. When I try to save the image as an io.BytesIO() array, the rotation seems to be lost.
The following code is called from save_model in the ModelAdmin code, and takes as input the UploadedFile from request.FILES, and returns an UploadedFile to be saved in the model FileField.
def rotate_image_from_exif(f):
logger.debug("rotate_image_from_exif START")
if isinstance(f, TemporaryUploadedFile): # this image is rotated correctly in the model
# large files in TemporaryUploadedFile
with open(f.temporary_file_path(), 'rb') as image_file:
image = pImage.open(image_file)
img = ImageOps.exif_transpose(image)
if 'exif' in image.info:
exif = image.info['exif']
img.save(f.temporary_file_path(), exif=exif)
img.save(f.temporary_file_path())
return f
elif isinstance(f, InMemoryUploadedFile):
image = pImage.open(f.file)
quality = 85
temp_path = '/tmp/fred.jpg'
img = ImageOps.exif_transpose(image)
img.save(temp_path, format=image.format, quality=quality) # this image is rotated correctly on the file system
img.seek(0)
output = io.BytesIO()
img.save(output, format=image.format, quality=quality)
output.seek(0)
return InMemoryUploadedFile(output,
'FileField', 'original_image', image.format,
sys.getsizeof(output), None) # this image is not rotated
else:
# can't read file
return None
I can solve this problem by setting FILE_UPLOAD_MAX_MEMORY_SIZE to something very small (say 1000), so all uploaded files are saved as TemporaryUploadedFiles, but I would really like to solve this issue with rotating an InMemoryUploadedFile.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
