Search code examples
plonedexterity

Image Field Validator for Specific Width/Height


I have a dexterity type, with image field definition looks like this:

image = NamedBlobImage(
    title=_(u'Lead Image'),
    description=_(u"Upload a Image of Size 230x230."),
    required=True,
)

How can I add a validator to check the uploaded image file? For example, if an image is over 500px in width, warn the user to upload another file. Hints or sample codes are appreciated.


Solution

  • You want to set a constraint function:

    from zope.interface import Invalid
    from foo.bar import MessageFactory as _
    
    
    def imageSizeConstraint(value):
        # value implements the plone.namedfile.interfaces.INamedBlobImageField interface
        width, height = value.getImageSize()
        if width > 500 or height > 500:
            raise Invalid(_(u"Your image is too large"))
    

    then set that function as the constraint of your NamedBlobImage field:

    image = NamedBlobImage(
        title=_(u'Lead Image'),
        description=_(u"Upload a Image of Size 230x230."),
        constraint=imageSizeConstraint,
        required=True,
    )
    

    See the Dexterity manual on validation for more information, as well as the plone.namedfile interface definitions.