在JSF中创建并显示缩略图(byte [])

时间:2010-02-18 12:04:46

标签: jsf thumbnails tomahawk

我正在将图片上传到服务器,当图片上传时,它应该会显示上传图片的大拇指。缩略图未保存在硬盘上我使用InputStream和OutputStream。对于上传我是ustig tomahawk。

我的index.jsp:

<h:form id="uploadForm" enctype="multipart/form-data">
  <t:inputFileUpload id="fileupload" 
    accept="image/*" 
    storage="file"
    value="#{fileUpload.uploadedFile}" 
    styleClass="fileUploadInput"
    required="true" 
    validator="epacient.FileUploadValidator"
    requiredMessage="Obvezna izbira datoteke." 
  />
  <br />
  <h:message for="fileupload" infoStyle="color: green;"
    errorStyle="color: red;" />
  <br />
  <h:commandButton value="Upload" id="fileUploadButton"
    action="#{fileUpload.upload}" />
  <h:message for="uploadForm" style="color: red;" />
  <h:graphicImage value="#{fileUpload.thumb}"
    rendered="#{fileUpload.uploaded}" />

</h:form>

fileUpload.upload调用函数String preview()

private  String thumb ;
public String preview() throws IOException{
  HttpServletResponse response = (HttpServletResponse)FacesContext
    .getCurrentInstance().getExternalContext().getResponse();
  try {
    FacesContext context = FacesContext.getCurrentInstance();
    Map requestMap = context.getExternalContext().getApplicationMap();
    byte[] bytes = (byte[])(requestMap.get("fileupload_bytes")); 
    // returns byte[]
    byte[] testByte = createThumbnail(bytes, 200);
    // here thumbnail is created
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}

createThumbnail:

public static byte[] createThumbnail( byte[] orig, int maxDim) {
  try {
    ImageIcon imageIcon = new ImageIcon(orig);
    Image inImage = imageIcon.getImage();
    double scale = (double) maxDim / (double) inImage.getWidth(null);

    int scaledW = (int) (scale * inImage.getWidth(null));
    int scaledH = (int) (scale * inImage.getHeight(null));

    BufferedImage outImage = new BufferedImage(scaledW, scaledH, BufferedImage.TYPE_INT_RGB);
    AffineTransform tx = new AffineTransform();

    if (scale < 1.0d) {
      tx.scale(scale, scale);
    }

    Graphics2D g2d = outImage.createGraphics();
    g2d.drawImage(inImage, tx, null);
    g2d.dispose();  

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(outImage, "JPG", baos);
    byte[] bytesOut = baos.toByteArray();

    return bytesOut;
  } catch (IOException e) {
    System.out.println("Erro: " + e.getMessage());
    e.printStackTrace();
  }
  return null;
}

现在我有我的缩略图,但它在byte[]可以任何身体告诉我如何用<h:graphicImage>标签显示我的拇指?或任何其他方式。

谢谢!

4 个答案:

答案 0 :(得分:9)

图像将每个图像计为单独请求。您无法处理 HTML响应(JSF)和单个请求/响应周期中的图像。您需要将图像/拇指存储在数据存储区中的某个位置,该数据存储区的寿命比请求长,例如服务器的本地磁盘文件系统(临时文件夹?webcontent文件夹?),或数据库(临时表?),或在会话中。

首先,替换

<h:graphicImage value="#{fileUpload.thumb}" ...

通过

<h:graphicImage value="thumbs/#{fileUpload.thumbId}" ...

以便生成为

<img src="thumbs/123" ...

src应该指向有效网址

然后,创建一个HttpServlet映射到url-pattern /thumbs/*并实现doGet()大致如下:

Long thumbId = Long.valueOf(request.getPathInfo().substring(1)); // 123
byte[] thumb = getItFromDiskOrDatabaseOrSessionByThumbId(thumbId);
String filename = getOriginalFilenameOfUploadedImageOrInventOne();

response.setContentType(getServletContext().getMimeType(filename));
response.setContentLength(thumb.length);
response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\"");

BufferedInputStream input = null;
BufferedOutputStream output = null;

try {
    input = new BufferedInputStream(new ByteArrayInputStream(thumb));
    output = new BufferedOutputStream(response.getOutputStream());
    byte[] buffer = new byte[8192];
    int length;
    while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
} finally {
    if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
    if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}

就是这样。可以在this article中找到更多servlet提示。

答案 1 :(得分:3)

graphicImage标记在HTML响应中生成img标记。因此,您需要在value标记的graphicImage属性中提供图片的网址,该属性与src标记的img属性相对应。

你可以:

  • filesystem上的缩略图写入可通过HTTP从外部访问的路径中。然后,您可以直接在value的{​​{1}}属性中引用该图片,例如graphicImage
  • 写一个/myapp/thumbnail/12345,在请求时提供图片。 servlet可以从内存(servlet),文件系统或数据库中读取映像,也可以每次生成它。在这种情况下,您需要将参数传递给servlet,例如HttpSession

简而言之,您需要将/myapp/thumbnail.do?filename=12345缩略图存储在某个位置(会话,文件系统,数据库),以便能够直接或通过servlet将其作为常规资源提供。

答案 2 :(得分:1)

Richfaces已经为你抽象了这个。检查<a4j:mediaOutput> - 您只需将byte[]写入组件提供的OutputStream

答案 3 :(得分:0)

谢谢ewernli。我重用了你的createThumbnail util方法。我添加了这个小增强功能,以便在宽度小于规定的maxDim宽度时返回原始图像。我这样做是因为我遇到了一种情况,即该方法返回的图像比原始图像大,用黑色像素填充。

        ImageIcon imageIcon = new ImageIcon(orig);
        Image inImage = imageIcon.getImage();

        int origWidth = inImage.getWidth(null);
        if(origWidth < maxDim) {
            return orig;
        }

        ...