在JSF中创建和显示缩略图(字节[]) [英] Create and show thumbnail (byte[]) in JSF

查看:107
本文介绍了在JSF中创建和显示缩略图(字节[])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将图像上传到服务器,并且在上传图像时,应该向我显示已上传图像的缩略图.缩略图未保存在硬盘上,我使用InputStream和OutputStream.对于上传,我是ustig战斧.

I'm uploading image to server and when image is uploaded it should show me a thumb of uploaded image. Thumbnail is not saved on hard disc I use InputStream and OutputStream. For upload i'm ustig tomahawk.

我的index.jsp:

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

fileUpload.upload calls function 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:

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>标签的拇指吗?或其他任何方式.

Now I have my thumbnail but it is in byte[] can any body tell me how to show my thumb with <h:graphicImage> tag? Or any other way.

谢谢!

推荐答案

这些图像均作为单独请求进行计数.您不能在单个请求/响应周期中同时处理HTML响应(JSF的)和图像.您需要将图片/缩略图存储在比请求寿命更长的数据存储区中的某个位置,例如服务器的本地磁盘文件系统(临时文件夹?webcontent文件夹?)或数据库(临时表?),或者在会话中.

The images counts each as a separate request. You cannot process both the HTML response (of JSF) and the image in a single request/response cycle. You need to store the image/thumb somewhere in a datastore which lives longer than a request, e.g. the server's local disk file system (temp folder? webcontent folder?), or a database (temp table?), or in the session.

首先,替换

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

作者

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

以使其生成为

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

(src应该指向有效网址)

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

Then, create a HttpServlet which is mapped on an url-pattern of /thumbs/* and implement doGet() roughly like follows:

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) {}
}

就是这样.可以在本文中找到更多servlet提示.

That's it. More servlet hints can be found in this article.

这篇关于在JSF中创建和显示缩略图(字节[])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆