代码之家  ›  专栏  ›  技术社区  ›  user2896120

不允许图像小于特定尺寸

  •  0
  • user2896120  · 技术社区  · 7 年前

    我有一个保存用户配置文件图像的模型。如果上载的图像大于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()
    

    当图像的宽度或高度小于200px时,不应上载该图像。但是,正在上载图像。我怎样才能阻止这种事发生?

    1 回复  |  直到 7 年前
        1
  •  2
  •   ruddra    7 年前

    而不是在 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
    

    原因是,当你打电话 保存() ,图像已上载。所以最好以形式来做。