【问题标题】:Can we obtain height and width of an image based on org.primefaces.model.UploadedFile in a JSF managed bean itself?我们可以根据 JSF 托管 bean 本身中的 org.primefaces.model.UploadedFile 获取图像的高度和宽度吗?
【发布时间】:2014-03-25 10:01:41
【问题描述】:

我们能否根据 JSF 托管 bean 本身中的 org.primefaces.model.UploadedFile 在其侦听器中获取通过 <p:fileUpload> 上传的图像的尺寸?

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.
}

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

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();

但是我们能否在文件实际存储在磁盘上之前获得这些维度,以便在服务层之前对其进行验证?

我正在使用,

  • PrimeFaces 4.0
  • JSF 2.2.6

在 JSF 托管 bean 中将图像写入磁盘很笨拙且无法完成,因为它需要更多关于文件大小调整的代码等等。此外,仅当有关该图像的其他信息成功存储到相关数据库中时,才应将文件写入磁盘。另外,PrimeFaces file upload validators don't work.

【问题讨论】:

  • 我认为您无法在保存文件之前获得尺寸。如果尺寸无效,则可以执行另一个步骤从磁盘中删除文件。

标签: image jsf file-upload primefaces jsf-2.2


【解决方案1】:

是的,你可以。您所需要的只是某种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);

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2014-02-16
    • 2010-11-18
    • 1970-01-01
    相关资源
    最近更新 更多