【问题标题】:Django Form Imagefield validation for certain width and height特定宽度和高度的 Django 表单图像字段验证
【发布时间】:2019-07-25 08:44:32
【问题描述】:

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

class Adv(models.Model):

    image = models.ImageField(upload_to=r'photos/%Y/%m/',
        width_field = ?,
        height_field = ?,
        help_text='Image size: Width=1080 pixel. Height=1920 pixel',

【问题讨论】:

    标签: django height width imagefield


    【解决方案1】:

    你可以通过两种方式做到这一点

    1. 模型验证

      从 django.core.exceptions 导入验证错误

      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")
      

    【讨论】:

    • 我正在寻找在字段中显示消息的解决方案(例如,如果电子邮件的格式不正确,那么您会看到“电子邮件无效。请提供有效的电子邮件”的消息,我想要这种类型的如果上传的照片不符合要求,则会显示消息。
    • 你可以改变ValidationError里面的信息
    • 尝试了第一种方法:在模型中验证并得到 django 'File' object has no attribute 'height' 错误。为了使其正常工作,请从作业中删除文件部分,如下所示:height = image.heightwidth = image.width
    【解决方案2】:

    我们需要一个像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)])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2016-01-27
      相关资源
      最近更新 更多