Skip to content

Instantly share code, notes, and snippets.

@caiolopes
Last active October 4, 2022 14:50
Show Gist options
  • Save caiolopes/a9f2bd942fa2d18412ac0d68a915eedf to your computer and use it in GitHub Desktop.
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!
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()
@NeoHimu
Copy link

NeoHimu commented Dec 12, 2019

img.convert('RGB').save(in_mem_file, format='JPEG')

add .convert() function to chnage RGBA image into RGB else JPEG formatting won't work

@lmielke
Copy link

lmielke commented Oct 4, 2022

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