背景:摄像头抓拍的图片,高清之类的,图片比较大,可能几百KB之类的,在展示的时候,往往只是展示缩略图,只有点击图片之后才会展示高清图,
直接在tomcat中添加拦截器,对图片请求进行过滤,来实现图片处理服务。
PictureFilter.java
package myweb; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class PictureFilter implements Filter{ private Pattern p = Pattern.compile("h_([0-9]*),w_([0-9]*)"); @Override public void destroy() {} @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; String queryStr = request.getQueryString(); String uri = request.getRequestURI(); if(isEmpty(queryStr)) { chain.doFilter(req, resp); }else { try { String picLocalPath = request.getSession().getServletContext().getRealPath(uri); String x_oss_process = request.getParameter("x-oss-process"); imageResize(picLocalPath, resp.getOutputStream(), x_oss_process); } catch (Exception e) { e.printStackTrace(); chain.doFilter(req, resp); } } } /** * * @param picLocalPath * @param output * @param paramters 格式"image/resize,m_fill,h_100,w_200" */ private void imageResize(String picLocalPath,OutputStream output,String x_oss_process) throws Exception{ // 解析x_oss_process参数 Matcher m = p.matcher(x_oss_process); boolean b = m.find(); if(!b){ return; } int h = Integer.parseInt(m.group(1)); int w = Integer.parseInt(m.group(2)); InputStream input = new FileInputStream(picLocalPath); BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) image.getGraphics(); BufferedImage img = ImageIO.read(input); g.drawImage(img, 0, 0, w, h, null); input.close(); String format = getSuffix(picLocalPath); ImageIO.write(image, format, output); } private String getSuffix(String str) { int index = str.lastIndexOf("."); if(index < 0) { return null; } return str.substring(index+1); } @Override public void init(FilterConfig conf) throws ServletException {} private boolean isEmpty(String str) { if(str==null || str.trim().length()==0) { return true; } return false; } }
web.xml中添加
<filter> <filter-name>pictureFilter</filter-name> <filter-class>myweb.PictureFilter</filter-class> </filter> <filter-mapping> <filter-name>pictureFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
想要多大多小,自己参数设置就可以了。
说明:这样做,对服务器的压力之类的没有测试过,这个对服务器的cpu肯定消耗变高了,对网络带宽的要求降低了,这里针对每一张图片每一次请求如果设置的处理参数相同,都进行了图片处理,没有进行缓存处理。可以考虑缓存来存放已经处理过一次的图片,定期清理缓存。
使用:将编译后的class文件直接放入tomcat对应的classes目录下面,在server.xml中添加过滤器配置,就可以生效。