Alex Rivera | Logout

Howto validate image upload in PlayFramework 1?

Asked 2011-07-10T23:11:37.047
11

I have to upload pictures with a few conditions :

  • dimensions cannot exceed x pixels height, y pixels width,
  • size cannot exceed b bytes on disk
  • has to be a PNG or a JPG file
  • has to be "resized"
  • has to be saved to disk (using play's Blob)

Si far, I've found little to no information on image upload and/or check for Play!Framework. Any help is welcome!

Thanks!

Edit
Report

1 Answer

13

After searching a little in PlayFramework's source code, I've stumbled upon ImageIO ibrary already used in Play. Cannot understand, why such easy checks have not been added to the core library...

Here's the check part, I've created for :

  • dimension check,
  • type check,
  • size check.

    package validators;
    
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    
    import play.Logger;
    import play.data.validation.Check;
    import play.db.jpa.Blob;
    import play.i18n.Messages;
    
    public class ImageValidator extends Check {
    
      public final static int MAX_SIZE = 4048;
      public final static int MAX_HEIGHT = 1920;
    
      @Override
      public boolean isSatisfied(Object parent, Object image) {
    
        if (!(image instanceof Blob)) {
            return false;
        }
    
        if (!((Blob) image).type().equals("image/jpeg") && !((Blob) image).type().equals("image/png")) {
            return false;
        }
    
        // size check
        if (((Blob) image).getFile().getLength() > MAX_SIZE) {
            return false;
        }
    
    
        try {
            BufferedImage source = ImageIO.read(((Blob) image).getFile());
            int width = source.getWidth();
            int height = source.getHeight();
    
            if (width > MAX_WIDTH || height > MAX_HEIGHT) {
                return false;
            }
        } catch (IOException exption) {
            return false;
        }
    
    
        return true;
        }
    }
    
answered 2011-07-11T09:24:03.990

Your Answer