【问题标题】:Saving images with pixels in django在 django 中保存带像素的图像
【发布时间】:2017-02-20 21:22:30
【问题描述】:

我想保存具有特定像素的图像,当有人在 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

【问题讨论】:

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


    【解决方案1】:
    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)
    

    【讨论】:

      猜你喜欢
      • 2014-06-05
      • 1970-01-01
      • 2020-05-08
      • 2014-12-27
      • 2018-05-16
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多