Skip to content

Instantly share code, notes, and snippets.

@mattandrews
Created January 13, 2018 15:10
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 mattandrews/c4d3f8da98744b23b857e886d88b4d0d to your computer and use it in GitHub Desktop.
Save mattandrews/c4d3f8da98744b23b857e886d88b4d0d to your computer and use it in GitHub Desktop.
Django thumbnails for admin
def resize_images(image_field):
pathname, filename = path.split(image_field.path)
img_file = Image.open(image_field.path)
# Convert to RGB
if img_file.mode not in ('L', 'RGB'):
img_file = img_file.convert('RGB')
# Save a thumbnail file for each of the given dimensions,
# prefixed with med_, small_ etc
IMAGE_SIZES = {
'med_': (250, 250),
'small_': (100, 100)
}
# each of which corresponds to an ImageField of the same name
for field_name, size in IMAGE_SIZES.iteritems():
working = img_file.copy()
working.thumbnail(size, Image.ANTIALIAS)
working.save(pathname + '/' + field_name + filename, working.format, quality=70)
class Foo(models.Model):
image = models.ImageField('Image', upload_to='images/')
def save(self):
super(Foo, self).save()
resize_images(image_field=self.image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment