来源:https://blog.csdn.net/tototuzuoquan/article/details/48354387
1.要想制作图片裁剪功能,可以使用网上的裁剪工具JCrop,网址是:https://github.com/tapmodo/Jcrop/
案例效果如下:
2.引入JCrop的js代码,具体要引入那些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='overflow: hidden;'> <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代码(注意这里的280和175表示的是我要一张长为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组件(FileUpload的js组件) $('#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]); }; |
5 编写后端代码:
/** * 上传图片的临时目录,截图前的预览,不保存 * * @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; } |
6 获取图片的宽高的代码:
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; } |
7 压缩与等比缩放的代码:
private void zoomOutImg(String saveURL) throws IOException { int ratio = operatorImage.getImgRatio(saveURL, CommonVar.LOGO_SCALE); operatorImage.reduceImageEqualProportion(saveURL, saveURL, ratio); } |
8 操作图片资源的工具类:
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 |