java用流的方式把图片写入response

private static Map imageContentType = new HashMap <>();
static {
imageContentType . put ( "jpg" , "image/jpeg" );
imageContentType . put ( "jpeg" , "image/jpeg" );
imageContentType . put ( "png" , "image/png" );
imageContentType . put ( "tif" , "image/tiff" );
imageContentType . put ( "tiff" , "image/tiff" );
imageContentType . put ( "ico" , "image/x-icon" );
imageContentType . put ( "bmp" , "image/bmp" );
imageContentType . put ( "gif" , "image/gif" );
}
 
  
httpServletResponse.setDateHeader("Expires", 0L);
httpServletResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
httpServletResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream out = null;

/*****method一:由于ImageIO.read不支持较大尺寸有时候会有错误*************/
BufferedImage image = ImageIO.read(new File(filePath));
out = httpServletResponse.getOutputStream();
ImageIO.write(image, "jpg", out);
out.flush();
/*****method二:直接用文件流来处理有更好的通用性*******************************************************/
File image = new File(filePath);
FileInputStream inputStream = new FileInputStream(image);
int length = inputStream.available();
byte data[] = new byte[length];
httpServletResponse.setContentLength(length);
String fileName = image.getName();
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
httpServletResponse.setContentType(FormatUtils.imageContentType.get(fileType));
inputStream.read(data);
OutputStream toClient = httpServletResponse.getOutputStream();
toClient.write(data);
toClient.flush();

你可能感兴趣的:(java)