Jcrop图片剪切实例

一.创建一个弹出窗
1.html代码
<div id="BgDiv"></div>
<div id="imgEditArea" style="display:none;top:0;">
    <h2><fmt:message key="productDetail.lbl.editImg"/><a href="#" id="btnClose" onclick="javascript:closeDiv('imgEditArea')"><fmt:message key="productDetail.lbl.closeDiv"/></a></h2>
    <table border='0'>
        <tr>
            <td>
                <div class="jc-demo-box" id="divPreview">
                      <img src="<c:url value="/files/BusiLic/shuiyin.jpg"/>" id="target" alt="[Jcrop Example]" />
                </div>
            </td>
            <td valign="top" align="center" id="tdImg">
                <div id="preview-pane" style="margin:30px">
                    <div class="preview-container" id="preview-container">
                         <img src="<c:url value="/files/BusiLic/shuiyin.jpg"/>" id="imgView" class="jcrop-preview" alt="Preview" />
                    </div>
                  </div>
                <form  enctype="multipart/form-data" id="uploadform" method="post" name="form2">
                    <div id="uploadBox">
                        <input type="file" name="file" id="file" onchange="PreviewImage(this,'target','divPreview')" size="6"/><br/><br/>
                        <input type="submit"  value="<fmt:message key="productDetail.lbl.saveImg"/>" id="btnSave" value="upload"></input>
                    </div>
                    <br/><fmt:message key="productDetail.lbl.msgImg"/>
                </form>
            </td>
        </tr>
    </table>    
</div>
2.css代码
#BgDiv{background-color:#FFFFFF; position:absolute; z-index:99; left:0; top:0; display:none; width:100%; height:100%;opacity:0.5;filter: alpha(opacity=50);-moz-opacity: 0.5;}
 .s_tab td{border:0;}    
    
#imgEditArea{position:absolute;width:90%; left:5%; top:0%; margin-left:0px; margin-top:300px;;height:auto; z-index:100;background-color:#fff; border:1px #8FA4F5 solid; padding:1px;}
#imgEditArea h2{ height:25px; font-size:14px; background-color:#8FA4F5; position:relative; padding-left:10px; line-height:25px;}
#imgEditArea h2 a{position:absolute; right:5px; font-size:12px; color:#000000}
#imgEditArea .form{padding:10px;}

3.弹出层展现
function ShowDIV(thisObjID) {
    $("#BgDiv").css({ display: "block", height: $(document).height() });
    $("#" + thisObjID ).css("top", "10px");
    $("#" + thisObjID ).css("display", "block");
}
4.弹出层隐藏
function closeDiv(thisObjID) {
    if(api!=null){
        api.destroy();    
    }
 
    $("#target").attr("src","<c:url value="/files/BusiLic/shuiyin.jpg"/>");
    $("#imgView").attr("src","<c:url value="/files/BusiLic/shuiyin.jpg"/>");
    $("#x").val("");
     $("#y").val("");
     $("#w").val("");
     $("#h").val("");
    $("#BgDiv").css("display", "none");
    $("#" + thisObjID).css("display", "none");
}
二.图片选择显示截取并保存
1. 创建两个<img>
    <div class="jc-demo-box" id="divPreview">
          <img src="<c:url value="/files/BusiLic/shuiyin.jpg"/>" id="target" alt="[Jcrop Example]" />
    </div>

    <div id="preview-pane" style="margin:30px">
        <div class="preview-container" id="preview-container">
             <img src="<c:url value="/files/BusiLic/shuiyin.jpg"/>" id="imgView" class="jcrop-preview" alt="Preview" />
        </div>
     </div>
2. 图片选取和保存图片
<form  enctype="multipart/form-data" id="uploadform" method="post" name="form2">
    <div id="uploadBox">
        <input type="file" name="file" id="file" onchange="PreviewImage(this,'target','divPreview')" size="6"/><br/><br/>
        <input type="submit"  value="<fmt:message key="productDetail.lbl.saveImg"/>" id="btnSave" value="upload"></input>
    </div>
    <br/><fmt:message key="productDetail.lbl.msgImg"/>
</form>
3. 选取图片,并在改区域显示
//js本地图片预览,兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3
    function PreviewImage(fileObj,imgPreviewId,divPreviewId){
        $("#x").val("");
        $("#y").val("");
        $("#w").val("");
        $("#h").val("");
        if(api!=null){
            api.destroy();    
        }
        var divId;
        var allowExtention=".jpg,.bmp,.gif,.png";//允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;
        var extention=fileObj.value.substring(fileObj.value.lastIndexOf(".")+1).toLowerCase();            
        var browserVersion= window.navigator.userAgent.toUpperCase();
        if(allowExtention.indexOf(extention)>-1){ 
            if(fileObj.files){//HTML5实现预览,兼容chrome、火狐7+等
                if(window.FileReader){
                    var reader = new FileReader(); 
                    reader.onload = function(e){
                        document.getElementById(imgPreviewId).setAttribute("src",e.target.result);
                        $("#imgView").attr("src",$("#"+imgPreviewId).attr("src"));
                        createJCrop(imgPreviewId);
                    };  
                    reader.readAsDataURL(fileObj.files[0]);
                }else if(browserVersion.indexOf("SAFARI")>-1){
                    alert(getMessage(msgE0042));
                }
            }else if (browserVersion.indexOf("MSIE")>-1){
                $("#uploadform").ajaxForm({
                    url:"/BML/file/proimg/iesrc",
                    type:"post",
                    dataType:"json",
                    success:function(data){
                    $("#"+imgPreviewId).attr("src","/BML/files/proInfo/temp/"+data.seriName);
                    $("#imgView").attr("src","/BML/files/proInfo/temp/"+data.seriName);
                    createJCrop(imgPreviewId);
                    },error:function(){
                        alert(getMessage(msgE0005, uploadPic));
                    }
                 });
                $("#uploadform").submit();
            }else if(browserVersion.indexOf("FIREFOX")>-1){//firefox
                var firefoxVersion= parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
                if(firefoxVersion<7){//firefox7以下版本
                    document.getElementById(imgPreviewId).setAttribute("src",fileObj.files[0].getAsDataURL());
                    $("#imgView").attr("src",$("#"+imgPreviewId).attr("src"));
                    createJCrop(imgPreviewId);
                }else{//firefox7.0+                    
                    document.getElementById(imgPreviewId).setAttribute("src",window.URL.createObjectURL(fileObj.files[0]));
                    $("#imgView").attr("src",$("#"+imgPreviewId).attr("src"));
                    createJCrop(imgPreviewId);
                }
            }else{
                document.getElementById(imgPreviewId).setAttribute("src",fileObj.value);
                $("#imgView").attr("src",$("#"+imgPreviewId).attr("src"));
                $(".jcrop-preview").attr("src",$("#"+imgPreviewId).attr("src"));
                createJCrop(imgPreviewId);
            }         
        }else{
            alert(getMessage(msgE0041));
            fileObj.value="";//清空选中文件
            if(browserVersion.indexOf("MSIE")>-1){                        
                fileObj.select();
                document.selection.clear();
            }                
            fileObj.outerHTML=fileObj.outerHTML;
        }
    }
3. 创建jcrop,图片剪切区域选择最主要的函数
    function createJCrop(divId,width,height) {
        // Create variables (in this scope) to hold the API and image size
         var jcrop_api,
            boundx,
             boundy,

             // Grab some information about the preview pane
             $pcnt = $('#preview-pane .preview-container'),
             $pimg = $('#preview-pane .preview-container img'),

             xsize = $pcnt.width(),
             ysize = $pcnt.height();
         
         api = $.Jcrop('#'+divId, {
                onSelect :updatePreview,
                onChange :updatePreview,
                setSelect: [ 125, 125, 250, 250 ],
                aspectRatio : 1
            });
         var bounds = api.getBounds();
              boundx = bounds[0];
              boundy = bounds[1];
            // Store the API in the jcrop_api variable
            jcrop_api = api;
            //$preview.appendTo(jcrop_api.ui.holder);
         
         function updatePreview(c)
         {
             var rx = width / c.w;
            var ry = height / c.h;
            var ow = $("#"+divd).width();
            var oh = $("#"+divd).height();
            
            $("#w").attr("value",Math.round(rx * ow));
            $("#h").attr("value",Math.round(ry * oh));
            $("#x").attr("value",Math.round(rx * c.x));
            $("#y").attr("value",Math.round(ry * c.y));
             if (parseInt(c.w) > 0)
             {
                 var rx = xsize / c.w;
                 var ry = ysize / c.h;

                 $pimg.css({
                       width: Math.round(rx * boundx) + 'px',
                       height: Math.round(ry * boundy) + 'px',
                       marginLeft: '-' + Math.round(rx * c.x) + 'px',
                       marginTop: '-' + Math.round(ry * c.y) + 'px'
                 });
              }
         };
    }
4.    用4个<input type="hidden">用于存放图片截取的坐标和长宽
    <input type="hidden" id="x" /><br/>
    <input type="hidden" id="y" /><br/>
    <input type="hidden" id="w" /><br/>
    <input type="hidden" id="h" /><br/>
5. 截取图片后保存
$("#uploadform").ajaxForm({
    url:"/BML/file/proimg/uploadImg?point="+cutPoint,
    type:"post",
    dataType:"json",
    success:function(data){
        var browserVersion= window.navigator.userAgent.toUpperCase();
        if(api!=null){
            api.destroy();    
        }
        if (browserVersion.indexOf("MSIE")>-1){
            if(browserVersion.indexOf("MSIE 6")>-1){//ie6                    
                $("#target1").attr("src","/BML/files/proInfo/"+data.seriName);
            }else{//ie[7-9]
                $("#target1").attr("src","/BML/files/proInfo/"+data.seriName);
                //document.getElementById("targetNew").setAttribute("src","/BML/files/proInfo/"+data.seriName);
            }
        }else{
            $("#target1").attr("src","/BML/files/proInfo/"+data.seriName);
        }
        $("#picpath0").val(data.seriName);
    },error:function(){
         alert(getMessage(msgE0043));
    }
});
6.图片保存
1.form表单提交,把文件传到后台。
2.jsp代码
$("#uploadform").ajaxForm({
    url:"/BML/file/proimg/uploadImg?point="+cutPoint,
    type:"post",
    dataType:"json",
    success:function(data){
        var browserVersion= window.navigator.userAgent.toUpperCase();
        f(api!=null){
            api.destroy();    
        }
        if (browserVersion.indexOf("MSIE")>-1){
            if(browserVersion.indexOf("MSIE 6")>-1){//ie6                    
                $("#target1").attr("src","/BML/files/proInfo/"+data.seriName);
            }else{//ie[7-9]
                $("#target1").attr("src","/BML/files/proInfo/"+data.seriName);
                //document.getElementById("targetNew").setAttribute("src","/BML/files/proInfo/"+data.seriName);
            }
        }else{
            $("#target1").attr("src","/BML/files/proInfo/"+data.seriName);
        }
        $("#picpath0").val(data.seriName);
    },error:function(){
         alert(getMessage(msgE0043));
    }
});

closeDiv('imgEditArea');
3.后台java代码
@RequestMapping("/proimg/uploadImg")
public @ResponseBody FileHandResult uploadCutImg( Model model,@RequestParam MultipartFile file,@RequestParam String point,HttpServletRequest request,HttpServletResponse response) throws Exception{
    String[] str=point.split(",");
    String x = str[0];
    String y = str[1];
    String w = str[2];
    String h = str[3];                
    int width = Integer.parseInt(w);
    int height = Integer.parseInt(h);
    int rx = Integer.parseInt(x);
    int ry = Integer.parseInt(y);
        
    FileHandResult res = new FileHandResult();
    if(file.getSize()>1000000){
        res.setResult(FileHandResult.REQUEST_FAIL);
        model.addAttribute("msg","图片尺寸太大");
        return null;
    }
    FileInputStream is = null ;
    ImageInputStream iis = null;
    try {
        String name = file.getOriginalFilename();//文件名
        String ext = "jpg";
        //String seriName = name.substring(0,name.lastIndexOf("."))+new Date().getTime()+"."+ext;
        String seriName = "proInfo"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"."+ext;
        String path = request.getSession().getServletContext().getRealPath("/files/proInfo");//文件路径
            
        File srcfile = new File(path+File.separator+seriName);
            
        Image image =ImageIO.read(file.getInputStream());
        BufferedImage tag = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //根据比例缩放图片
        tag.getGraphics().drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH),0,0,null);
        FileOutputStream out = new FileOutputStream(srcfile);  
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
        encoder.encode(tag);  
        out.close();  
                
        is = new FileInputStream(srcfile);
        iis = ImageIO.createImageInputStream(is);
            
        Iterator<ImageReader> it= ImageIO.getImageReadersByFormatName(ext);
        ImageReader reader = it.next();
        reader.setInput(iis);
            
        ImageReadParam param =  reader.getDefaultReadParam();
        //根据坐标点长宽截取图片
        Rectangle rect = new Rectangle(rx,ry,170,170);
        param.setSourceRegion(rect);
            
        BufferedImage bi = reader.read(0, param);
        ImageIO.write(bi, ext, new File(path+File.separator+seriName));
        res.setSeriName(seriName);
    } catch (Exception e) {
        throw new Exception();
    }finally{
        if(is!=null){
            is.close() ;       
            if(iis!=null)
            iis.close();  
        }
    }
        
    response.setContentType("text/html");
    res.setResult(FileHandResult.REQUEST_OK);
    return res;
}

 

posted @ 2014-07-01 20:54  箜篌  阅读(2158)  评论(0编辑  收藏  举报