5

Can we obtain dimensions of an image uploaded via <p:fileUpload> in its listener based on org.primefaces.model.UploadedFile in a JSF managed bean itself?

import java.io.IOException;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

public void fileUploadListener(FileUploadEvent event) throws IOException
{
    UploadedFile uploadedFile = event.getFile();
    //Do something to obtain the height and the width of the uploaded image here.
}

These dimensions can be obtained in various ways after storing the image on a disk like,

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

File file = new File("File path");
byte[] byteArray = IOUtils.toByteArray(uploadedFile.getInputstream());
// Or byte[] byteArray = uploadedFile.getContents();
FileUtils.writeByteArrayToFile(file, byteArray);

BufferedImage image=ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();

But can we obtain these dimensions before the file is actually stored on a disk so that it can be validated far before the service layer?

I'm currently using,

  • PrimeFaces 4.0
  • JSF 2.2.6

Writing images to a disk in a JSF managed bean is clumsy and cannot be done, since it requires much more code regarding file resize and many more. Moreover, files should only be written to a disk, if other information regarding that image is stored successfully into the database in question. Also, PrimeFaces file upload validators don't work.

Community
  • 1
  • 1
Tiny
  • 27,221
  • 105
  • 339
  • 599
  • i dont think you can get the dimensions before the file is saved. If the dimensions are not valid, then you can do another step to delete the file from the disk. – ZEE Mar 25 '14 at 11:52

1 Answers1

8

Yes you can. All you need is some kind of InputStream so that ImageIO can create the BufferedImage - use a ByteArrayInputStream!

byte[] image = uploadedFile.getContents();
BufferedImage bi = ImageIO.read(new ByteArrayInputStream(image));
int width = bi.getWidth();
int height = bi.getHeight();
System.out.println("Width: " + width + ", height: " + height);
Manuel
  • 3,828
  • 6
  • 33
  • 48