不允许图片小于特定尺寸

时间:2019-01-31 06:22:04

标签: django django-models django-views

我有保存用户简档的图像的模型。如果上传的图片大于200x200像素,则我们将尺寸调整为200x200。如果图片的尺寸正确在200x200,那么我们将返回该图片。我现在想要的是抛出一个错误给用户说,这个形象是太小,是不允许的。这是我所拥有的:

class Profile(models.Model):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    user    = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    bio     = models.CharField(max_length=200, null=True)
    avatar  = models.ImageField(upload_to="img/path")
    gender  = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True)

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)
        if self.avatar:
            image = Image.open(self.avatar)
            height, width = image.size
            if height == 200 and width == 200:
                image.close()
                return

            if height < 200 or width < 200:
                return ValidationError("Image size must be greater than 200")
            image = image.resize((200, 200), Image.ANTIALIAS)
            image.save(self.avatar.path)
            image.close()

当图像的宽度或高度小于200像素时,不应上传该图像。但是,正在上传图像。我该如何阻止这种情况的发生?

1 个答案:

答案 0 :(得分:2)

您可以采用以下形式来代替执行save()方法:

from django.core.files.images import get_image_dimensions
from django import forms

class ProfileForm(forms.ModelForm):
   class Meta:
       model = Profile

   def clean_avatar(self):
       picture = self.cleaned_data.get("avatar")
       if not picture:
           raise forms.ValidationError("No image!")
       else:
           w, h = get_image_dimensions(picture)
           if w < 200:
               raise forms.ValidationError("The image is %i pixel wide. It's supposed to be more than 200px" % w)
           if h < 200:
               raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
       return picture

之所以这样做是因为,当您调用save()时,图像已经上传。因此最好采用表格形式。