Last active
October 4, 2022 14:50
-
-
Save caiolopes/a9f2bd942fa2d18412ac0d68a915eedf to your computer and use it in GitHub Desktop.
Function to resize an image of an ImageField from a Django model. It saves space on S3!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io | |
from django.core.files.storage import default_storage as storage | |
def save(self, *args, **kwargs): | |
super().save(*args, **kwargs) | |
img_read = storage.open(self.image.name, 'r') | |
img = Image.open(img_read) | |
if img.height > 300 or img.width > 300: | |
output_size = (300, 300) | |
img.thumbnail(output_size) | |
in_mem_file = io.BytesIO() | |
img.save(in_mem_file, format='JPEG') | |
img_write = storage.open(self.image.name, 'w+') | |
img_write.write(in_mem_file.getvalue()) | |
img_write.close() | |
img_read.close() |
Thanks a lot. This saved me after hours of searching. I had however change line 8 'r' to 'rb'
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
img.convert('RGB').save(in_mem_file, format='JPEG')
add .convert() function to chnage RGBA image into RGB else JPEG formatting won't work