网页图片优化 ImageMagick + im4java + nginx

来源:互联网 发布:十年来化学成就知乎 编辑:程序博客网 时间:2024/05/16 16:39
原路径__@宽_高.jpg
<img alt="" src="img__@55_55.jpg"


nginx代理

location /upload/ {    if (!-f $request_filename) {rewrite ^(.*)/upload/(.*)$ http://www.xxxxx.com/imagemagick?url=/upload/$2 break;    }            root   /home/xxxxx/;    expires 60;        }

servlet

package com.spring.web.servlet;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.io.OutputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import org.springframework.util.StringUtils;import com.spring.web.util.ImageTools;/** * Servlet implementation class ValidateCode */public class Image extends HttpServlet {        private static final Logger log = Logger.getLogger("R");        private static final long serialVersionUID = 1L;        public Image() {        super();    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        //设置相应类型,告诉浏览器输出的内容为图片                response.setContentType("image/jpg");         String url = request.getParameter("url").replace("/xieyun", "");         //String url = request.getRequestURI().replace("/xieyun", "");         String wl_url = request.getSession().getServletContext().getRealPath("/");         String all_url = wl_url + url;                  //log.error("url:" + url);         //log.error("all_url:" + all_url);         String[] arr = url.split("__@");         if(arr.length == 1) {             if(!new File(all_url).exists()) {                 imageOut(wl_url +"/images/member/tx.jpg", response);                 return;             } else {                 imageOut(all_url, response);                 return;             }         }         if(!new File(wl_url + arr[0]).exists()) {             imageOut(wl_url +"/images/member/tx.jpg", response);             return;         }         String originalName = arr[0].substring(arr[0].lastIndexOf("."));         Integer width = StringUtils.isEmpty(arr[1].split("_")[0])?null:Integer.parseInt(arr[1].split("_")[0]);         String xx = arr[1].split("_")[1];         Integer height = StringUtils.isEmpty(xx.substring(0,xx.lastIndexOf(".")))?null:Integer.parseInt(xx.substring(0,xx.lastIndexOf(".")));         String new_url = arr[0] + "__@" + (null==width?"":width) + "_" + (null==height?"":height) + ".jpg"/*originalName*/;         File file = new File(wl_url + new_url);         //log.error("new_url:" + new_url);         //log.error("wl_url + new_url:" + wl_url + new_url);         if(!file.exists()) {            try {                log.info("转换图片:" + width + ","+ height + ","+ wl_url + arr[0] + ","+ wl_url + new_url);                ImageTools.cutImage(width, height, wl_url + arr[0], wl_url + new_url);                imageOut(wl_url + new_url, response);                return;            } catch (Exception e) {                log.error(e.getMessage());                e.printStackTrace();                imageOut(all_url, response);                return;            }         } else {             imageOut(wl_url + new_url, response);             return;         }    }        public void imageOut(String imagePath, HttpServletResponse response) throws IOException {        FileInputStream fis = new FileInputStream(imagePath);          int size =fis.available(); //得到文件大小            byte data[]=new byte[size];           fis.read(data);  //读数据            fis.close();           response.setContentType("image/jpg"); //设置返回的文件类型            OutputStream os = response.getOutputStream();          os.write(data);          os.flush();          os.close();              }}


/**  * Copyright(c)2013 Wuxi Lanlin Co.,Ltd. * All right reserved. */ package com.spring.web.util;import org.im4java.core.ConvertCmd;import org.im4java.core.IMOperation; /** * ImageMagick和im4java处理图片 * @author sunlightcs * 2011-6-1 * http://hi.juziku.com/sunlightcs/ */public class ImageTools {         /**     * ImageMagick的路径     */    public static String imageMagickPath = "C:\\Program Files\\ImageMagick-6.9.2-Q16";         static{        /**         * 获取ImageMagick的路径         */        //Properties prop = new PropertiesFile().getPropertiesFile();        //linux下不要设置此值,不然会报错        //imageMagickPath = prop.getProperty("imageMagickPath");        }              /**     * 根据坐标裁剪图片     *      * @param srcPath   要裁剪图片的路径     * @param newPath   裁剪图片后的路径     * @param x   起始横坐标     * @param y   起始挫坐标     * @param x1  结束横坐标     * @param y1  结束挫坐标     */    public static void cutImage(String srcPath, String newPath, int x, int y, int x1, int y1)  throws Exception {        int width = x1 - x;        int height = y1 - y;        IMOperation op = new IMOperation();        op.addImage(srcPath);                 /**         * width:裁剪的宽度         * height:裁剪的高度         * x:裁剪的横坐标         * y:裁剪的挫坐标         */        op.crop(width, height, x, y);                 op.addImage(newPath);                 ConvertCmd convert = new ConvertCmd();                 //linux下不要设置此值,不然会报错        //convert.setSearchPath(imageMagickPath);                 convert.run(op);    }         /**     * 根据尺寸缩放图片     * @param width  缩放后的图片宽度     * @param height  缩放后的图片高度     * @param srcPath   源图片路径     * @param newPath   缩放后图片的路径     */    public static void cutImage(Integer width, Integer height, String srcPath, String newPath) throws Exception {        IMOperation op = new IMOperation();        op.addImage(srcPath);                 op.resize(width, height);        op.addImage(newPath);         ConvertCmd convert = new ConvertCmd();                //linux下不要设置此值,不然会报错        //convert.setSearchPath("C:\\ImageMagick-6.9.2-Q16");                 convert.run(op);    }              /**     * 根据宽度缩放图片     * @param width  缩放后的图片宽度     * @param srcPath   源图片路径     * @param newPath   缩放后图片的路径     */    public static void cutImage(int width, String srcPath, String newPath) throws Exception {        IMOperation op = new IMOperation();        op.addImage(srcPath);                          op.resize(width, null);        op.addImage(newPath);                 ConvertCmd convert = new ConvertCmd();                 //linux下不要设置此值,不然会报错        //convert.setSearchPath(imageMagickPath);                 convert.run(op);    }                        /**     * 给图片加水印     * @param srcPath   源图片路径     */    public static void addImgText(String srcPath) throws Exception {        IMOperation op = new IMOperation();        op.font("宋体").gravity("southeast").pointsize(18).fill("#BCBFC8").draw("text 5,5 juziku.com");                        op.addImage();        op.addImage();        ConvertCmd convert = new ConvertCmd();                 //linux下不要设置此值,不然会报错        //convert.setSearchPath(imageMagickPath);         convert.run(op,srcPath,srcPath);    }              public static void main(String[] args) throws Exception{        //cutImage("D:\\apple870.jpg", "D:\\apple870eee.jpg", 98, 48, 370, 320);        cutImage(400,600, "E:/01_200_300.jpg", "E:/01_200_300.jpg");        //addImgText("//home//steven//a.jpg");    }}