Search code examples
pythondjangoimagefile-uploadimage-resizing

Saving images with pixels in django


I want to save images with specific pixels, when someone uploads image on django models it will be resized and then save according to id. I want them to be saved in path product/medium/id. I have tried defining path in it which saves image but not on the path I want.

Here is my models.py

class Product(models.Model):
product_name = models.CharField(max_length=100)
product_description = models.TextField(default=None, blank=False, null=False)
product_short_description = models.TextField(default=None,blank=False,null=False,max_length=120)
product_manufacturer = models.CharField(choices=MANUFACTURER,max_length=20,default=None,blank=True)
product_material = models.CharField(choices=MATERIALS,max_length=20,default=None,blank=True)
No_of_days_for_delivery = models.IntegerField(default=0)
product_medium = models.ImageField(upload_to='product/id/medium',null=True,blank=True)

def save(self, *args, **kwargs):
    self.slug = slugify(self.product_name)
    super(Product, self).save(*args, **kwargs)

Now on this, I want to resize the image get it's id and save in path product/medium/id/image.jpg


Solution

  • from PIL import Image
    import StringIO
    import os
    from django.core.files.uploadedfile import InMemoryUploadedFile
    
    
    class Product(models.Model):
        pass  # your model description
    
        def save(self, *args, **kwargs):
            """Override model save."""
            if self.product_medium:
                img = Image.open(self.image)
                size = (500, 600) # new size
                image = img.resize(size, Image.ANTIALIAS) #transformation
                try:
                    path, full_name = os.path.split(self.product_medium.name)
                    name, ext = os.path.splitext(full_name)
                    ext = ext[1:]
                except ValueError:
                    return super(Product, self).save(*args, **kwargs)
                thumb_io = StringIO.StringIO()
                if ext == 'jpg':
                    ext = 'jpeg'
                image.save(thumb_io, ext)
    
                # Add the in-memory file to special Django class.
                resized_file = InMemoryUploadedFile(
                    thumb_io,
                    None,
                    name,
                    'image/jpeg',
                    thumb_io.len,
                    None)
    
                # Saving image_thumb to particular field.
                self.product_medium.save(name, resized_file, save=False)
    
            super(Product, self).save(*args, **kwargs)