我们可以在JSF托管bean本身中基于org.primefaces.model.UploadedFile获取图像的高度和宽度吗?

Tin*_*iny 4 jsf file-upload image primefaces jsf-2.2

我们可以<p:fileUpload>基于org.primefaces.model.UploadedFileJSF托管bean本身获取通过其侦听器上传的图像的维度吗?

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.
}
Run Code Online (Sandbox Code Playgroud)

将图像存储在磁盘上之后,可以通过各种方式获得这些尺寸,

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();
Run Code Online (Sandbox Code Playgroud)

但是,我们可以在文件实际存储在磁盘上之前获取这些维度,以便可以在服务层之前验证它吗?

我正在使用,

  • PrimeFaces 4.0
  • JSF 2.2.6

将图像写入JSF托管bean中的磁盘是笨拙的,无法完成,因为它需要更多关于文件大小调整的代码等等.此外,如果有关该图像的其他信息成功存储到相关数据库中,则只应将文件写入磁盘.此外,PrimeFaces文件上载验证程序不起作用.

Man*_*uel 7

是的你可以.所有你需要的是某种形式的InputStream,这样ImageIO可以创建BufferedImage-使用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);
Run Code Online (Sandbox Code Playgroud)