JCrop+GraphicsMagick+Im4Java 实现图像裁减

Im4Java的安装文档见:http://blog.csdn.net/tangpengtao/article/details/9208047css

JCrop的插件:jquery.Jcrop.jshtml

jQuery之Jcropjava

安装GraphicsMagick 和IM4JAVA:http://blog.sina.com.cn/s/blog_872758480100xufm.html

IM4Java的jar:im4java-1.2.0.jarjquery

jcrop的调用js以下:linux

        /**
         * 上传头像成功后保存
         * @param file
         */
        uploadMyPicSuccess: function(file, data){
            var filePath = data.path; // 附件地址
            var width = data.width; // 原图宽度
            var height = data.height; // 原图高度
            var containWidth = 445;
            var containHeight = 314;
            
            var marginLeft = (containWidth - width) / 2;
            var marginTop = (containHeight - height) / 2;
            //截取区域的图片
            $("#img_1").css({width:width, height:height, "margin-left":marginLeft, "margin-top":marginTop})
                    .attr("src", fileURL+'/'+data.path);
                        //50*50规格
            $("#img_3").attr("src", fileURL+'/'+data.path);
                        //120*120规格
            $("#img_2").attr("src", fileURL+'/'+data.path);
            if(jcrop) jcrop.destroy();
             var jcrop = $.Jcrop("#img_1", {
                aspectRatio: 1,
                onChange: showPreview,
                 //showPreview为裁剪图片的function,后面写
                onSelect: showPreview,
                setSelect: [ 0, 0, 100, 100]
            });
            $(".jcrop-holder").css({"margin-left":marginLeft, "top":marginTop});
            
            //建立隐藏域,保存头像真实存储路径
            $("#newUrl").val(filePath);
            //点击预览按钮
            $("#previewBtn").show().click(function(){
                cropPic();
            });
            // 获取裁剪后的图片,预览
            function cropPic(){
                var mypic =$("#newUrl").val();
                $.ajax({
                    async: false,
                    type: "POST",
                    dataType:"json",
                    cache: false,
                    url: baseURL +"/userinfo/cropPic",//裁剪图片的action
                    data: "imageX=" +cropImage.x + "&imageY=" + cropImage.y + "&imageWidth=" + cropImage.w + "&imageHeight=" + cropImage.h + "&fileUrl=" + encodeURIComponent(mypic),
                    success: function(data){
                        if(data.success){
                            var smallPicUrl = data.path.split(",")[0];
                            var normalPicUrl = data.path.split(",")[1];
                            
                            // 建立隐藏域,保存小图
                            $("#smallUrl").val(smallPicUrl);
                            $("#img_3").attr("src", fileURL+"/" + smallPicUrl);
                            $("#img_2").attr("src", fileURL+"/" + normalPicUrl);
                            // 激活保存按钮
                            $("#saveBtn").show();
                            
                            
                        }
                    },
                    error:function(data){
                        alert("更新失败,请从新上传 ");
                    }
                });
            }

        },

定义裁剪预览:ajax

//图片裁剪预览
window.cropImage =  {};
//选中裁剪内容后,获取裁剪坐标
function showPreview(coords){
    cropImage.x = coords.x;
    cropImage.y = coords.y;
    cropImage.w = coords.w==0?1:coords.w;
    cropImage.h = coords.h==0?1:coords.h;
}

 图片处理:json

1.图片上传后,假设显示图片的区域为413*350,则,上传后,把图片按原有的尺寸,等比裁减windows

    /**
     * 上传我的头像
     * @param request
     * @param response
     * @param file 上传的图片
     * @param width 界面裁剪控件的宽度
     * @param height 界面裁剪控件的高度
     * @throws IOException
     */
    @RequestMapping(value = "/uploadHeadPic")
    public void uploadHeadPic(HttpServletRequest request,
            HttpServletResponse response, @RequestParam("file")
            MultipartFile file, @RequestParam(value="width",defaultValue="445")int width, 
            @RequestParam(value="height",defaultValue="314") int height) throws IOException {
        if (logger.isDebugEnabled()) {
            logger.debug("头像上传开始");
        }
        // 响应JSON
        Map<String, Object> result = new HashMap<String, Object>();
        boolean success = false;
        String fileName = file.getOriginalFilename();
        // 生成一个临时文件名
        fileName = "tmp_" + GenUUIDHelper.genFileName(fileName);
        if (FileUtils.isPicture(fileName)) {
            Map<String, Object> r = fileManage.resizePicture(file.getInputStream(),fileName,request.getSession().getServletContext().getRealPath("/"), width, height);
            String url = (String) r.get("path");
            if (url != null) {
                result.put("path", url.replace("\\", "/"));
                result.put("width", r.get("width"));
                result.put("height", r.get("height"));
                success = true;
            } else {
                success = false;
            }
        }
        result.put("success", success);
        if (logger.isDebugEnabled()) {
            logger.debug("swf上传结束");
        }
        // 输出响应,文件上传不支持ajax方式的响应contentType,因此不能使用ResponseBody
        response.setCharacterEncoding(HttpUtil.ENCODING_UTF8);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
            objectMapper.writeValue(jsonGenerator, result);
            response.getOutputStream().flush();
        } catch (IOException e) {
            logger.error("writeResponse", e);
        }

    }

2.点击预览后,按尺寸 120*120 和 50*50裁减2张图片,并返回图片路径,作为预览图片app

    /**
     * 裁剪我的头像;
     * @param request
     * @param response
     * @param x
     * @param y
     * @param width
     * @param height
     * @param fileUrl
     * @throws Exception
     */
    @RequestMapping(value = "/cropPic")
    public void cropPic(HttpServletRequest request, HttpServletResponse response,
            @RequestParam("imageX") Double x,
            @RequestParam("imageY") Double y,
            @RequestParam("imageWidth") Double width,
            @RequestParam("imageHeight") Double height,
            @RequestParam("fileUrl") String fileUrl) throws Exception{
        if (logger.isDebugEnabled()) {
            logger.debug("裁剪我的头像开始");
        }
        String contentPath=request.getSession().getServletContext().getRealPath("/");
        fileUrl = contentPath + File.separator + fileUrl;
        if (logger.isDebugEnabled()) {
            logger.debug("fileUrl="+fileUrl);
        }
        Map<String, Object> resultMap = new HashMap<String, Object>();
        File imgFile = new File(fileUrl);
        if (imgFile.exists()) {
            if (logger.isDebugEnabled()) {
                logger.debug("imgFile.exists...........");
            }
            // 压缩并保存文件
            String[] fileKey = fileManage.cropPicture(fileUrl, contentPath,x.intValue(), y.intValue(), width.intValue(), height.intValue());
            resultMap.put("success", true);
            resultMap.put("path", fileKey[0].replace("\\", "/") + "," + fileKey[1].replace("\\", "/"));
        }else{
            resultMap.put("success", false);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("swf裁剪我的头像结束");
        }
        
        // 输出响应,文件上传不支持ajax方式的响应contentType,因此不能使用ResponseBody
        response.setCharacterEncoding(HttpUtil.ENCODING_UTF8);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
            objectMapper.writeValue(jsonGenerator, resultMap);
            response.getOutputStream().flush();
        } catch (IOException e) {
            logger.error("writeResponse", e);
        }
    }

3.共用的图片处理类:async

@Component()
public class Im4JavaPictureHandle implements IPictureHandle {
    private static Log logger = LogFactory.getLog(Im4JavaPictureHandle.class);
    
    @Override
    public void cropImage(String srcPath, String newPath, int x, int y, int width,
            int height, int saveWidth, int saveHeight)  throws Exception {
        
        IMOperation op = new IMOperation();
        op.addImage(srcPath);
        
        /**
         * width:裁剪的宽度
         * height:裁剪的高度
         * x:裁剪的横坐标
         * y:裁剪的挫坐标
         */
        op.crop(width, height, x, y);
        op.resize(saveWidth, saveHeight);
        op.addImage(newPath);
        
        ConvertCmd convert = new ConvertCmd(true);
        
        //linux下不要设置此值,否则会报错
        if(!System.getProperty("os.name").equals("Linux")&&!StringUtils.isNullOrEmpty(FileConsts.GRAPHICS_MAGICK_PATH))
        {
            convert.setSearchPath(FileConsts.GRAPHICS_MAGICK_PATH);
        }
        convert.run(op);
    }
    @Override
    public int[] resizeImage(String srcPath, String newPath, int width,
            int height)  throws Exception {
        int[] target = scaleWidthAndHight(srcPath,width,height);
        width = target[0];
        height = target[1];
        IMOperation op = new IMOperation();
        op.addImage(srcPath);
        op.resize(width, height);
        op.addImage(newPath);
        
        ConvertCmd convert = new ConvertCmd(true);
      
        //linux下不要设置此值,否则会报错
        if(!System.getProperty("os.name").equals("Linux")&&!StringUtils.isNullOrEmpty(FileConsts.GRAPHICS_MAGICK_PATH))
        {
            convert.setSearchPath(FileConsts.GRAPHICS_MAGICK_PATH);
        }
        convert.run(op);
        return target;
    }
   
    public int[] scaleWidthAndHight(String srcPath,int w,int h) throws IOException{
        Image srcImage = null;
        int[] target = new int[2];
        
        FileInputStream oldIs = new FileInputStream(srcPath);
        
        srcImage = javax.imageio.ImageIO.read(oldIs);
        
        //获得图片原始大小,以便按比例压缩
        int width = srcImage.getWidth(null);
        int height = srcImage.getHeight(null);
        
        
        // 特殊处理 当w和h均为0时,长,宽默认为图片原大小
        if(w==0 && h==0){
            w = width;
            h = height;
        }else if(h==0){
            
            if(width>=w){
                 h = (int)Math.round((height * w * 1.0 / width));
            }else{
                w = width;
                h = height;
            }
        }
        else{
            
             if ( width >= height){
                 if(width >= w){
                     h = (int)Math.round((height * w * 1.0 / width));
                 }else{
                      w = width;
                      h = height;
                  }
             }else{
                 if(height >= h ){
                      w = (int)Math.round((width * h * 1.0 / height));
                  }else{
                      w = width;
                      h = height;
                  }
             }
            
        }
        target[0] = w;
        target[1] = h;
        oldIs.close();
        return target;
    }
}

在linux和windows下的安装分别以下:

http://www.cnblogs.com/jennybackup/p/3951935.html

相关文章
相关标签/搜索