使用JCrop進行圖片裁剪,裁剪js說明,裁剪預覽,裁剪上傳,裁剪設計的圖片處理的工具類和代碼

來源:https://blog.csdn.net/tototuzuoquan/article/details/48354387

1.要想製作圖片裁剪功能,可以使用網上的裁剪工具JCrop,網址是:https://github.com/tapmodo/Jcrop/

案例效果如下:

2.引入JCropjs代碼,具體要引入那些js可以參考JCrop案例:

3.編寫的html代碼如下:

<div id="light" class="white_content">

       <div class="vatitlee">

           封面截取

           <div class="guan">

              <a href="javascript:void(0)"

                  onClick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">X</a>

           </div>

       </div>

 

       <div class="tailoringc">

           <div class="tailoringl">

              <img id="jcrop_target"

                  src="<c:url value="/resources/cartoon2/images/images/banner7.jpg"/>"

                  width="280" height="553" />

           </div>

 

           <div class="tailoringr" style='overflowhidden;'>

              <img id="cutImgId"

                  src="<c:url value="/resources/cartoon2/images/images/banner7.jpg"/>"

                  width="280" height="553" />

           </div>

 

           <div class="clear"></div>

       </div>

       <div class="tailoringb">

           <a class="button" href="javascript:void(0)" onclick="saveUploadImg()">裁剪</a>

           <a href="javascript:void(0)" class="button"

               onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">取消</a>

       </div>

    </div>

4編寫JS代碼(注意這裏的280175表示的是我要一張長爲280px像素高175px像素的圖片):

//封面上傳,截圖

//上傳後返回的文件名

    var filename;

    var fileid;

    //裁剪主要用到了jcrop_api

    var jcrop_api,boundx,boundy;

    //原始文件名稱

    var originalfilename;

    //實際圖片的寬高

    var imgweight,imgheight;

    //dx:實際圖片寬/顯示寬度

    //dy實際圖片高/顯示高度

    //scale:最終縮放比

//  var dx,dy,scale = 1;

//  var displayW = 175, displayH = 350;

    var imgObj = new Image();

   

    $(function() {

       init();

    });

   

    function init() {

       //文件上傳的js組件(FileUploadjs組件)

       $('#uploadCover').fileupload({

            dataType: 'json',

            //autoUpload: true,

            url:'/contentAffix/upTemp',

           

            done: function (e, data) { 

                if(jcrop_api!=null){

                   jcrop_api.destroy();

                }

                $.each(data.result, function (index, file) {

                    if(index=='filedesc') {

                       //獲取文件名稱

                       filename=file.filename;

                       //實際的文件高度

                       imgweight = file.imgweight;

                       //實際的文件寬度

                       imgheight = file.imgheight;

                      

//                     //設置縮放比例

//                     dx = imgweight / displayW;

//                     dy = imgheight / displayH;

//                     if(dx > dy && dy > 1) {

//                         scale = dx;

//                        

//                     }

//                     if(dy > dx && dx > 1) {

//                         scale = dy;

//                     }

//                    

//                     displayW = imgweight / scale;

//                     displayH = imgheight / scale;

                      

//                     $("#jcrop_target").css({

//                        width:displayW + 'px',

//                        height:displayH + 'px'

//                     });

//                     $(".tailoringc .tailoringl").css({

//                        width:(displayW + 2) + 'px',

//                        height:(displayH + 2) + 'px'

//                     });

                      

                       originalfilename = file.originalfilename;

                       fileid=file.id;

                       $('#light').show();

                     $('#fade').show();

                    

                       var imgurl = file.filepath+'/'+file.filename;

                       $('#jcrop_target').attr('src',imgurl);

                       $('#cutImgId').attr('src',imgurl);

                      

                       cutPic();

                       //重新加載圖像到jcrop,才能小圖上正確顯示截圖位置

                       //jcrop_api.setImage(imgurl);

                    }

                });

            },

        });

       $("#pickCover").click(function () {

           $("#uploadCover").trigger('click');

       });

      

       $('body').data('filelist'new Array());

    }

   

//點擊裁剪時做的操作

//傳遞到後臺的是最終在實際圖片上的位置和寬高

    function saveUploadImg(){

        c = jcrop_api.tellSelect();

        if (parseInt(c.w) > 0) {

            $.ajax({

                  url:'/cartoon-web/contentAffix/cutimageAndSaveAffix',

                  data :{"pointx":Math.round(c.x * imgweight / 280),"pointy":Math.round(c.y * imgheight / 350),"pointw":Math.round(c.w * imgweight / 280),"pointh":Math.round(c.h * imgheight / 350),"filename":filename,"fileid":fileid,"originalfilename":originalfilename},

                  dataType:'json',

                 

                  success: function(data){

                     if(data.result == "success"){

                         $("#fmimg").attr('src', data.cropImgPath+"?r="+new Date().getTime());

                    

                         $('input[type=hidden][name=coverAffixId]').val(fileid);

                        

                         $('#light').hide();

                         $('#fade').hide();

                        

                         displayW = 280;

                         displayH = 350;

                     }else{

                         alert("請選擇圖片");

                     }

                  }

            });

        } 

    }

   

    //保存上傳後的文件名稱

    function saveReuploadImg(){

       c = jcrop_api.tellSelect();

       var affixId = $('#coverAffixId').val();

        $.ajax({

           url:'/cartoon-web/contentAffix/cutimageAndUpdateAffix',

           data :{

              "pointx":Math.round(c.x),

              "pointy":Math.round(c.y),

              "pointw":Math.round(c.w),

              "pointh":Math.round(c.h),

              "filename":filename,

              "fileid":fileid,

              "originalfilename":originalfilename,

              "affixId":affixId

           },

           dataType:'json',

           success: function(data){

              if(data.result == "success") {

                  $("#fmimg").attr('src', data.cropImgPath+"?r="+new Date().getTime());

                  $('input[type=hidden][name=coverAffixId]').val(fileid);

                  $('#light').hide();

                  $('#fade').hide();

              }else{

                  alert("請選擇圖片");

              }

           }

       });

    }

   

    //顯示預覽

    function showPreview(c){

       if (parseInt(c.w) > 0) {

          

           var rx = 280 / c.w;

           var ry = 175 / c.h;

           var bounds = jcrop_api.getBounds();

           boundx = bounds[0];

           boundy = bounds[1];

          

           $('#cutImgId').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',

           });

       }

    }

 

    function cutPic(){

       imgObj = new Image();

       imgObj.src = jcrop_target.src;

      

       jcrop_api = $.Jcrop('#jcrop_target',{

            onChange: showPreview,//選框改變時的事件

            onSelect: showPreview,//選框選定時的事件

            handleSize:1,//縮放按鈕大小

            drawBorders:false,//繪製邊框

            aspectRatio: 280/175,//選框寬高比。說明:width/height

            allowResize:true,

            allowSelect:false//允許新選框

         //   bgColor:"#ccc",  //背景色

//          minSize: [50,50],

//          allowMove: true,

//          allowResize:false,

//          allowSelect:true, //允許新選框

//          cornerHandles:false,  //允許邊角縮放

//          sideHandles:false,  //允許四邊縮放

//          handleSize:9,

//          drawBorders:true, //繪製邊框

            dragEdges:true,  //允許拖動邊框

//         //bgOpacity:0.9, //透明度

//           onChange:showPreview, //當選擇區域變化的時候,執行對應的回調函數

//          onSelect:showPreview, //當選中區域的時候,執行對應的回調函數

//          aspectRatio:1, //正方形

            //setSelect:[300,300,300,300,0,0]

        });

      

       //設置選擇框默認位置

       jcrop_api.animateTo([0,0,280,175]);

    };

編寫後端代碼:

/**

     上傳圖片的臨時目錄,截圖前的預覽,不保存

     *

     @param param

     @param imageFile

     @return

     */

    @ResponseBody

    @RequestMapping(value = "/upTemp", method = RequestMethod.POST, produces = "application/json")

    public Map<String, Object> upTemp(@RequestParam Map<String, String> param,

           @RequestParam("file") MultipartFile imageFile) {

 

       Map<String, Object> result = new HashMap<String, Object>();

       if (!imageFile.isEmpty()) {

 

           Map<String, String> filedesc = new HashMap<String, String>();

 

           String uuid = FileUtils.genFileName();// uuid形成的文件名稱

 

           String filename = uuid;

           try {

              // 新文件名

              String uuIDFileName = uuid;

 

              // 存放路徑

              String path = CommonVar.getLocalTempPath()

                     + FileUtils.genFilePathCover(FilePathType.COVER);

              path = path.replace("\\""/").replace("//""/");

 

              // 原文件名

              String srcName = imageFile.getOriginalFilename();

 

              // 新文件名

              String newFileName = uuIDFileName

                     + srcName.substring(srcName.indexOf("."));

 

              // 保存文件路徑(臨時文件夾下)

              String saveURL = path + "/" + newFileName;

              LOGGER.debug(saveURL);

 

              // 寫文件

              InputStream fi = imageFile.getInputStream();

              FileUtils.writeFile(fi, saveURL);

 

              // 等比縮圖

              zoomOutImg(saveURL);

              int[] imgWH = getImageWH(saveURL);

 

              String webpath = CommonVar.getWebTempPath()

                     + FileUtils.genFilePathCover(FilePathType.COVER);

              webpath = webpath.replace("\\""/");

 

              filedesc.put("id", uuid);

              // filedesc.put("filetype", "3");

              filedesc.put("contenttype", imageFile.getContentType());

              filedesc.put("name", filename);// uuid

              filedesc.put("filename", newFileName);// 有後綴

              filedesc.put("originalfilename",

                     imageFile.getOriginalFilename());

              filedesc.put("filepath", webpath);

              filedesc.put("imgweight", imgWH[0] + "");

              filedesc.put("imgheight", imgWH[1] + "");

 

              result.put("filedesc", filedesc);

 

           catch (Exception e) {

              e.printStackTrace();

           }

       }

       return result;

    }

獲取圖片的寬高的代碼:

private int[] getImageWH(String saveURL) {

       int[] imgWH = { 0, 0 };

       try {

           BufferedImage bimg = operatorImage.getBufferedImage(saveURL);

           imgWH[0] = bimg.getWidth();

           imgWH[1] = bimg.getHeight();

       catch (IOException e) {

           e.printStackTrace();

       }

 

       return imgWH;

    }

壓縮與等比縮放的代碼:

private void zoomOutImg(String saveURL) throws IOException {

       int ratio = operatorImage.getImgRatio(saveURL, CommonVar.LOGO_SCALE);

       operatorImage.reduceImageEqualProportion(saveURL, saveURL, ratio);

    }

操作圖片資源的工具類:

package com.kuman.cartoon.utils;

 

import java.awt.AlphaComposite;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Point;

import java.awt.Rectangle;

import java.awt.color.ColorSpace;

import java.awt.image.BufferedImage;

import java.awt.image.ColorConvertOp;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Iterator;

import java.util.List;

 

import javax.imageio.ImageIO;

import javax.imageio.ImageReadParam;

import javax.imageio.ImageReader;

import javax.imageio.stream.ImageInputStream;

 

import org.springframework.stereotype.Service;

 

import com.kuman.cartoon.common.CommonVar;

 

//import com.sun.image.codec.jpeg.JPEGCodec;

//import com.sun.image.codec.jpeg.JPEGImageEncoder;

 

@Service

public class OperateImage {

 

         public OperateImage() {

                   super();

         }

 

         /**

          對圖片裁剪,並把裁剪新圖片保存

          *

          * @param srcPath

          *            讀取源圖片路徑

          * @param toPath

          *            寫入圖片路徑

          * @param x

          *            剪切起始點x座標

          * @param y

          *            剪切起始點y座標

ly:Calibri;"> 

@Service

public class OperateImage {

 

         public OperateImage() {

                   super();

         }

 

         /**

          對圖片裁剪,並把裁剪新圖片保存

          *

          * @param srcPath

          *            讀取源圖片路徑

          * @param toPath

          *            寫入圖片路徑

          * @param x

          *            剪切起始點x座標

          * @param y

          *            剪切起始點y座標

          * @param width

          *            剪切寬度

          * @param height

          *            剪切高度

          * @param readImageFormat

          *            讀取圖片格式

          * @param writeImageFormat

          *            寫入圖片格式

          * @throws IOException

          */

         public void cropImage(String srcPath, String toPath, int x, int y,

    &n

相關文章
相關標籤/搜索