在django中使用像素保存图像

时间:2016-10-12 07:03:29

标签: python django image file-upload image-resizing

我想保存具有特定像素的图像,当有人在django模型上传图像时,它会被调整大小然后根据id保存。我希望它们保存在路径product / medium / id中。我已经尝试在其中定义保存图像但不在我想要的路径上的路径。

这是我的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)

现在,我希望调整图片大小获取它的ID并保存在路径product/medium/id/image.jpg

1 个答案:

答案 0 :(得分:0)

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)