4

我的 models.py 中有以下图像字段(请参见下面的代码)

我想设置图像的固定宽度和高度,使其始终为 100x100px

下面的代码是系统中已经存在的,我不确定宽度和高度是如何传递的,或者是否可以使用此代码将宽度和高度设置为固定大小。

image = models.ImageField(
        upload_to="profiles",
        height_field="image_height",
        width_field="image_width",
        null=True,
        blank=True,
        editable=True,
        help_text="Profile Picture",
        verbose_name="Profile Picture"
    )
    image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
    image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
4

1 回答 1

4
class ModelName(models.Model):    
    image = models.ImageField(
        upload_to="profiles",
        null=True,
        blank=True,
        editable=True,
        help_text="Profile Picture",
        verbose_name="Profile Picture"
    )
    image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
    image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")

    def __unicode__(self):
        return "{0}".format(self.image)

    def save(self):
        if not self.image:
            return            

        super(ModelName, self).save()
        image = Image.open(self.photo)
        (width, height) = image.size     
        size = ( 100, 100)
        image = image.resize(size, Image.ANTIALIAS)
        image.save(self.photo.path)
于 2013-02-28T16:31:46.010 回答