jsp接收到的byte[]类型怎么转为png图片显示在页面上?

JavaScript017

jsp接收到的byte[]类型怎么转为png图片显示在页面上?,第1张

用一个方法把byte[]写入命名的png文件中,然后放到web路径里,让jsp按照路径访问即可。

//将byte数组写入文件  

public void createFile(String path, byte[] content) throws IOException {   FileOutputStream fos = new FileOutputStream(path)  

  fos.write(content)  

  fos.close()  

}

在jsp调用时例子:

createFile(application.getRealPath(''/images")+"/mypic.png"), yourBytes)

然后用<img src="images/mypic.png">就行。

/**

* 通过servlet查看图片

* @param datas

* @param imgType

* @param response

* @throws IOException

*/

public void viewPic(byte[] datas, String imgType, HttpServletResponse response) throws IOException {

InputStream buffin = new ByteArrayInputStream(datas)// 业务逻辑取得图片的byte[]

ServletOutputStream sos =null// 将图像输出到Servlet输出流中。

try {

BufferedImage img = ImageIO.read(buffin)

// 禁止图像缓存。

response.setHeader("Pragma", "no-cache")

response.setHeader("Cache-Control", "no-cache")

response.setDateHeader("Expires", 0)

sos = response.getOutputStream()// 将图像输出到Servlet输出流中。

ImageIO.write(img, imgType, sos)

} catch (IOException e) {

e.printStackTrace()

} finally {

buffin.close()

sos.close()

}

}

参考文章: http://blog.csdn.net/sunny243788557/article/details/7903615