Skip to content

Instantly share code, notes, and snippets.

@rturowicz
Last active December 16, 2015 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rturowicz/5472429 to your computer and use it in GitHub Desktop.
Save rturowicz/5472429 to your computer and use it in GitHub Desktop.
django - ImageField scaled-down on the fly
# models.py: overwritten model save method
def save(self, *args, **kwargs):
if self.cover:
img_string = StringIO()
pil_image = Image.open(self.cover.file)
if pil_image:
res_image = pil_image.resize((1034, 1400))
res_image.save(img_string, pil_image.format)
# original image replaced by thumbnail
self.cover.file = InMemoryUploadedFile(
img_string,
self.cover.file.field_name,
self.cover.file.name,
self.cover.file.content_type,
img_string.len,
self.cover.file.charset
)
super(Issue, self).save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment