3

I am trying to validate the image dimension in form level and display a message to user if submitted photo does not meet requirement which is image dimension 1080x1920. I dont want to store the width and height size in database. I tried with the Imagefield width and height attribute. But it is not working.

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',
Jhon Doe
  • 113
  • 1
  • 11

2 Answers2

3

You can do it in two ways

  1. Validation in model

    from django.core.exceptions import 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. Cleaning in forms

            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")
    
Jibin Mathews
  • 1,129
  • 1
  • 10
  • 23
  • I am looking solution to display the message in field (e.g. if email is not in correct form then you see the message that "email is not valid. please provide valid email'' i want this type of message displayed if the uploaded photo does not fulfill requirement. – Jhon Doe Mar 04 '19 at 05:26
  • you can change the message inside ValidationError – Jibin Mathews Mar 04 '19 at 05:40
  • 1
    Tried first way: _Validation in model_ and got **django 'File' object has no attribute 'height**' error. In order to get it work remove the file part from assignments as folllowing: `height = image.height` and `width = image.width`. – Jaime Jun 10 '20 at 00:24
1

We need an image processing library such as PI to detect image dimension, here is the proper solution:

# 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

then in the model:

class Photo(models.Model):
    image = models.ImageField('Image', upload_to=image_upload_path, validators=[maximum_size(128,128)])
mrblue
  • 807
  • 2
  • 12
  • 24