zoukankan      html  css  js  c++  java
  • Servlet以流的形式返回图片

    代码:

    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageDecoder;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    
    public class Servlet2 extends HttpServlet {
    	// 设定输出的类型
    	private static final String GIF = "image/gif;charset=GB2312";
    	private static final String JPG = "image/jpeg;charset=GB2312";
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		/*String imagePath = "D:\1234.gif";*/
    		String imagePath = this.getServletContext().getRealPath("/img/1234.gif");//获取真实路径
    		response.reset();
    		OutputStream output = response.getOutputStream();// 得到输出流
    		if (imagePath.toLowerCase().endsWith(".jpg"))// 使用编码处理文件流的情况:
    		{
    			response.setContentType(JPG);// 设定输出的类型
    			// 得到图片的真实路径
    			// 得到图片的文件流
    			InputStream imageIn = new FileInputStream(new File(imagePath));
    			// 得到输入的编码器,将文件流进行jpg格式编码
    			JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(imageIn);
    			// 得到编码后的图片对象
    			BufferedImage image = decoder.decodeAsBufferedImage();
    			// 得到输出的编码器
    			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
    			encoder.encode(image);// 对图片进行输出编码
    			imageIn.close();// 关闭文件流
    		}
    		if (imagePath.toLowerCase().endsWith(".gif"))// 不使用编码处理文件流的情况:
    		{
    			response.setContentType(GIF);
    			 File file = new File(imagePath);
    	            FileInputStream fis = new FileInputStream(file);
    	            ServletOutputStream sos = response.getOutputStream();
    	            byte[] b = new byte[1024];
    	            int n;
    	            int l = 0;
    	            while ((n = fis.read(b)) != -1) {
    	                l = l + n;
    	                sos.write(b, 0, n);
    	            }
    	            response.setContentLength(l);
    	            fis.close();
    	            sos.close();
    		}
    		output.close();
    	}
    }
    
  • 相关阅读:
    MySQL数据库服务器的架设
    Ubuntu 16.04 LTS软件包管理基本操作
    2个 List<T>进行数据合并
    创建 cachingConfiguration 的配置节处理程序时出错: 未能加载文件或
    【转】.gitignore失效的解决办法
    【转】码农提高工作效率
    【转】从零开始编写自己的C#框架(7)——需求分析
    C#获取文件的绝对路径
    【转】类中如何引用server.MapPath()
    c# 运行时替换某文件源代码(将XML 转换成 某个枚举并写入源文件)
  • 原文地址:https://www.cnblogs.com/yuanchaoyong/p/7671130.html
Copyright © 2011-2022 走看看