Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we obtain height and width of an image based on org.primefaces.model.UploadedFile in a JSF managed bean itself?

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.

like image 768
Tiny Avatar asked Mar 20 '23 02:03

Tiny


1 Answers

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);
like image 186
Manuel Avatar answered Apr 05 '23 16:04

Manuel