java--有关前台展示图片流的用法

需求:前台展示图片,之前系统是从服务器磁盘路径中读取,当图片数量多的时候,由于读写操作耗时,就会导致页面出现卡的感觉。

解决方案:使用缓存技术,在第一次浏览过图片之后,将图片的byte[]流缓存到MAP中,下次在访问的时候直接缓存获取就可以。

样例代码:

jsp调用方式如下:

<img id="showImg" src="loadImage.action?picName=${pList }" width="110px" height="75px" />
在src中写入要跳转的地址,我这里用的是struts2

后台类的写法:

public void loadImage() throws Exception {
    ActionContext context = ActionContext.getContext();
    HttpServletResponse imgResponse = (HttpServletResponse) context
        .get(ServletActionContext.HTTP_RESPONSE);
    HttpServletRequest imgRequest = (HttpServletRequest) context
        .get(ServletActionContext.HTTP_REQUEST);

    String picName = imgRequest.getParameter("picName");
    String[] picNames = picName.split("/");
    String url = Constant.HDFS_PREFIX + Constant.HDFS_AD_PREFIX
        + picNames[picNames.length - 1];
    // 根据URL获取图片流
    byte[] picStream = ImgUtil.AD_PIC_MAP.get(url);
    InputStream in = new ByteArrayInputStream(picStream);
    BufferedOutputStream bout = new BufferedOutputStream(
        imgResponse.getOutputStream());
    try {
      byte b[] = new byte[1024];
      int len = in.read(b);
      while (len > 0) {
        bout.write(b, 0, len);
        len = in.read(b);
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      bout.close();
      in.close();
    }
  }
此处需要将byte[]流写入respose中,这样在前台页面就可以展示图片了。

以上是我工程的代码,可参照改成自己的项目。

参考网址: http://www.blogjava.net/focusJ/archive/2011/04/30/367243.html

原文地址:https://www.cnblogs.com/wh-king/p/4270017.html