日期:2014-05-17 浏览次数:20721 次
public class PrintImage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PrintImage() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @throws IOException
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedOutputStream outputStream =null;
InputStream fileInputStream = null;
try{
//这里没有设置charset=utf-8 是否有关?
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");
response.setDateHeader("Expires", 0);
System.out.println("PrintImage invoked");
//文件名称是页面传入的 路径是绝对路径 如/home/image/
File file = new File(SysParamUtil.getParam(SysParamConstants.FILE_UPLOAD_DISK)+ request.getParameter("fileName"));
if(!file.exists()) {
fileInputStream = request.getSession().getServletContext().getResourceAsStream("/ext/resources/images/nopic.gif");
} else {
fileInputStream = new FileInputStream(file);
}
BufferedImage bufferedImage = ImageIO.read(fileInputStream);
outputStream = new BufferedOutputStream(response.getOutputStream());
JPEGImageEncoder imageEncoder = JPEGCodec.createJPEGEncoder(outputStream);
JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(bufferedImage);
encodeParam.setQuality(1f, true);
imageEncoder.encode(bufferedImage, encodeParam);
byte[] data = new byte[8192];
int len = -1;
while((len = fileInputStream.read(data, 0, 8192)) != -1) {
outputStream.write(data, 0, len);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(outputStream !=null){
outputStream.flush();
outputStream.close();
}
if(fileInputStream != null){
fileInputStream.close();
}
}
}
}