Python 在django中使用像素保存图像

Python 在django中使用像素保存图像,python,django,image,file-upload,image-resizing,Python,Django,Image,File Upload,Image Resizing,我想保存具有特定像素的图像,当有人在django模型上上载图像时,它将调整大小,然后根据id进行保存。我希望它们保存在路径product/medium/id中。我已尝试在其中定义保存图像的路径,但不在我想要的路径上 这是我的模型。py class Product(models.Model): product_name = models.CharField(max_length=100) product_description = models.TextField(default=None, bl

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

这是我的模型。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

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)