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,
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With