Nitesh Rawat
Nitesh Rawat

Reputation: 81

saving multiple images with different dimensions from a single ImageField in django models

How can I save multiple images with dimensions(eg: 10x10, 20x20, 30x30) into the "/media/" folder using a single models.ImageField() in django models?

Thanks, Nitesh

Upvotes: 0

Views: 524

Answers (1)

Nitesh Rawat
Nitesh Rawat

Reputation: 81

Ah, finally did it using Pillow library(pip install Pillow) at the time of saving a model instance. You can override the def save() like:

from PIL import Image
import os
def save(self):
    super().save(*args, **kwargs)
    img = Image.open(self.image.path)
    output_size = (300, 300)
    img.thumbnail(output_size)
    image_name, image_ext = os.path.splitext(self.image.path)
    custom_path = '{}_300{}'.format(image_name, image_ext)
    img.save(custom_path)

Upvotes: 1

Related Questions