特定宽度和高度的Django Form Imagefield验证

时间:2019-03-04 04:01:04

标签: django height width imagefield

我正在尝试验证表单级别的图像尺寸,如果提交的照片不符合图像尺寸1080x1920的要求,则会向用户显示一条消息。我不想在数据库中存储宽度和高度大小。我尝试使用Imagefield width和height属性。但这不起作用。

INSERT

2 个答案:

答案 0 :(得分:0)

您可以通过两种方式完成

  1. 模型验证

    从django.core.exceptions

    导入ValidationError

    def validate_image(image):
        max_height = 1920
        max_width = 1080
        height = image.file.height 
        width = image.file.width
        if width > max_width or height > max_height:
            raise ValidationError("Height or Width is larger than what is allowed")
    
    class Photo(models.Model):
        image = models.ImageField('Image', upload_to=image_upload_path, validators=[validate_image])
    
  2. 表格清洁

            def clean_image(self):
                image = self.cleaned_data.get('image', False)
                if image:
                    if image._height > 1920 or image._width > 1080:
                        raise ValidationError("Height or Width is larger than what is allowed")
                    return image
                else:
                    raise ValidationError("No image found")
    

答案 1 :(得分:0)

我们需要一个图像处理库,例如 PI 来检测图像尺寸,这里是正确的解决方案:

# Custom validator to validate the maximum size of images
def maximum_size(width=None, height=None):
    from PIL import Image

    def validator(image):
        img = Image.open(image)
        fw, fh = img.size
        if fw > width or fh > height:
            raise ValidationError(
            "Height or Width is larger than what is allowed")
     return validator

然后在模型中:

class Photo(models.Model):
    image = models.ImageField('Image', upload_to=image_upload_path, validators=[maximum_size(128,128)])