首页 > 代码库 > 调用jquery.Jcrop.min.js 切割图片 实例
调用jquery.Jcrop.min.js 切割图片 实例
需求是:上传一个图片,然后将上传的这个图片进行切割。。。。。。。。
首先是jsp页面。页面需要引入js
<script src="http://www.mamicode.com/${fileUrlPrx}/scripts/wap/jquery.min.js"></script>
<script src="http://www.mamicode.com/${fileUrlPrx}/scripts/wap/jquery.Jcrop.min.js"></script>
注意几个隐藏域,这些是选中区域的点坐标,与长宽:
<input type="hidden" id="x" name="x" value="http://www.mamicode.com/0"/>
<input type="hidden" id="y" name="y" value="http://www.mamicode.com/0"/>
<input type="hidden" id="w" name="w" value="http://www.mamicode.com/0"/>
<input type="hidden" id="h" name="h" value="http://www.mamicode.com/0"/>
<%@ include file="/commons/taglibs.jsp" %><%@ page contentType="text/html;charset=UTF-8" %><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%><!DOCTYPE HTML><html> <head> <meta charset="utf-8" /> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"> <meta content="yes" name="apple-mobile-web-app-capable"> <meta content="black" name="apple-mobile-web-app-status-bar-style"> <meta name="format-detection" content="telephone=no"> <title>照片裁切</title> <link href="${fileUrlPrx}/skins/css/wap_hdcs.css" rel="stylesheet" type="text/css"> <link href="${fileUrlPrx}/skins/css/wap_jquery.Jcrop.min.css" rel="stylesheet" type="text/css"> <script src="${fileUrlPrx}/scripts/wap/jquery.min.js"></script> <script src="${fileUrlPrx}/scripts/wap/jquery.Jcrop.min.js"></script> <script src="${fileUrlPrx}/commons/js/WXUtil.js"></script> <style type="text/css"> #mainBox2{ width:300px; height:300px; position:absolute; left:50%; top:50%; margin:-100px 0 0 -100px; font-size: 16px; } .shadow{display: none;width:100%;height:100%;background:rgba(0,0,0,0.5);position:absolute;top:0;left:0;z-index:999;text-align:center;font-size:16px;font-weight:bold;color:#FFF;} </style> <script type="text/javascript"> WXUtil.setPrefix(‘${fileUrlPrx}‘); var memberId = ‘${memberId}‘; var photourl = ‘${photourl}‘; function initCut(){ if(navigator.userAgent.indexOf("windows Phone")>-0){ setTimeout("doCut()",1000); }else{ doCut(); } } function doCut(){ function updateCoords(c){ $(‘#x‘).val(c.x); $(‘#y‘).val(c.y); $(‘#w‘).val(c.w); $(‘#h‘).val(c.h); }; var wh = $("#clipArea").height(); var ww = $("#clipArea").width(); var cutHeight = 0 ; var cutWidth = 0 ; if(ww/wh>0.8566){ cutHeight = wh cutWidth = parseInt(cutHeight*0.8566) ; }else{ cutWidth = ww cutHeight = parseInt(cutWidth/0.8566) ; } $(‘#cropbox‘).Jcrop({ //minSize: [cutWidth,cutHeight], //maxSize:[cutWidth ,cutHeight], setSelect: [0,0,cutWidth, cutHeight], aspectRatio: 0.8566, onSelect: updateCoords }); function checkCoords(){ if(parseInt($.trim($(‘#w‘).val())) > 0){ return true; }; alert(‘请裁剪你所需要的照片。??‘); return false; }; $(‘.clipBtn a‘).click(function(){ checkCoords(); }); } var isSubmit = 0 ; $(function(){ $("#printThisPic").click(function(){ if(isSubmit==1){ alert("正在处理您的照片请稍后..."); return false ; } var code = $("#code").val(); if(code==""){ alert("请输入消费码"); return false ; } var msg = $("#msg").val(); if(code.length>42){ alert("为了保证打印效果,最多只能填写42个字"); return false ; } isSubmit = 1 ; var x = $("#x").val(); var y = $("#y").val(); var w = $("#w").val(); var h = $("#h").val(); var wh = $("#clipArea").height(); var ww = $("#clipArea").width(); $(document).scrollTop(0); var contentHeight = $(document).height(); $(‘#shadow‘).css(‘height‘,contentHeight).css(‘lineHeight‘,contentHeight/2 + ‘px‘).show(); $.post(‘${fileUrlPrx}wxcs/cutSuccess‘,{msg:msg,code:code,x: parseInt(x),y: parseInt(y),w:parseInt(w),h:parseInt(h),wh:parseInt(wh),ww:parseInt(ww),memberid: memberId,photourl: photourl},function(data){ if(data==‘1‘){ WXUtil.closeWxWindow(); }else if(data==‘2‘){ alert("系统错误,请重试。"); $(‘#shadow‘).hide(); isSubmit = 0 ; }else if(data==‘3‘){ alert("您的消费码输入错误。"); $(‘#shadow‘).hide(); isSubmit = 0 ; }else if(data==‘4‘){ alert("亲,设备离线了。"); $(‘#shadow‘).hide(); isSubmit = 0 ; }else if(data==‘4‘){ alert("亲,您的消费码已经被使用。"); $(‘#shadow‘).hide(); isSubmit = 0 ; } }); }); }); </script> </head> <body> <div class="clipBox box-size"> <div class="clipArea" id="clipArea"> <c:if test="${ errMsg != null }"> <div id="mainBox2"> <font style="color: red;font-weight: 700;font-size: 16px;">${errMsg}</font> </div> </c:if> <c:if test="${ errMsg == null }"> <div class="clipShow" id="clipShow"> <img id="cropbox" src="${fileUrlPrx}${photourl}" onl oad="initCut()"/> </div> </c:if> </div> <c:if test="${ errMsg == null }"> <textarea id="msg" placeholder="写上一句话吧!!" maxlength="42" class="shadowTextarea box-size"></textarea> <input id="code" type="text" placeholder="请输入消费码" class="shadowInp box-size"> <a href="javascript:void(0)" class="purpleBtn box-size" id="printThisPic">打 印</a> </c:if> </div> <div id="shadow" class="shadow">正在处理您的照片,请稍候...</div> <input type="hidden" id="x" name="x" value="0"/> <input type="hidden" id="y" name="y" value="0"/> <input type="hidden" id="w" name="w" value="0"/> <input type="hidden" id="h" name="h" value="0"/> </body></html>
然后是后台接收:
@RequestMapping(value="http://www.mamicode.com/cutSuccess") @ResponseBody public String cutSuccess(ModelMap model,HttpServletRequest request,HttpServletResponse response){ response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String memberid = request.getParameter("memberid"); String photourl = request.getParameter("photourl"); String code = request.getParameter("code"); String msg = request.getParameter("msg"); logger.info("start编辑照片..toCutImg...memberid="+memberid+",photourl="+photourl+",code="+code+",msg="+msg); int x = Integer.valueOf(request.getParameter("x")==null?"0":request.getParameter("x")); int y = Integer.valueOf(request.getParameter("y")==null?"0":request.getParameter("y")); int w = Integer.valueOf(request.getParameter("w")==null?"0":request.getParameter("w")); int h = Integer.valueOf(request.getParameter("h")==null?"0":request.getParameter("h")); int ww = Integer.valueOf(request.getParameter("ww")==null?"0":request.getParameter("ww")); int wh = Integer.valueOf(request.getParameter("wh")==null?"0":request.getParameter("wh")); logger.info("参数:x="+x+"\ty="+y+"\tw="+w+"\th="+h+"\tww="+ww+"\twh="+wh); ThdCsPrintLogQuery query = new ThdCsPrintLogQuery(); query.setMemberid(Long.valueOf(memberid)); query.setPhotourl(photourl); ThdCsPrintLog tplog = (ThdCsPrintLog)thdCsPrintLogManager.findPage(query).getResult().get(0); try { String filename = tplog.getPhotourl() ; String fileRealpath = request.getRealPath("/"); String code_filepath =fileRealpath+filename; File file = new File(code_filepath); BufferedImage tphotoImg = ImageIO.read(file); BufferedImage cutImg = eApiManager.cutImgComput(tphotoImg, w, h, x, y,ww,wh); //保存剪切之后的图片 String resultpicname = new Date().getTime()+""+CommonUtil.getRandNum(6)+"_cut.jpg"; String finalFilePath = "/upload/picmsg/"+tplog.getShopid()+"/"+resultpicname ; tplog.setCutpicurl(finalFilePath); thdCsPrintLogManager.update(tplog); File fileIn = new File(fileRealpath+finalFilePath); fileIn.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(fileIn); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); encoder.encode(cutImg); cutImg.flush(); os.close(); os.flush();// String res = getInfoAndSendMsg(tplog, code, memberid, msg,photourl) ; logger.info("end 编辑照片..toCutImg...memberid="+memberid+",photourl="+photourl+",code="+code); return res; } catch (Exception e) { e.printStackTrace(); return ("2 "); //系统错误 } }
其中,主要剪切方法:cutImgComput()
/** * 截图 * @param image 原图 * @param width 获取面宽 * @param height 获取面高 * @param x 获取面x * @param y 获取面y * @param pagew 展示页面宽 * @param pageh 展示页面高 * @return * @throws Exception */ public BufferedImage cutImgComput(BufferedImage image, int width, int height, int x, int y, int pagew,int pageh) throws Exception{ int oldW = image.getWidth(), oldH = image.getHeight(); // 原图横纵长、宽 int newW = width * oldW/pagew; // 新宽度 = 页面截图宽 * 原图宽/展示div宽度 int newH = height * oldH/pageh; // 新高度 = 页面截图高 * 原高宽/展示div高度 int newX = x * oldW/pagew; // 新X坐标 = 选择x坐标 * 原图宽/展示div宽度 int newY = y * oldH/pageh;// 新Y坐标 = 选择y坐标 * 原高宽/展示div高度 ImageFilter cropFilter = new CropImageFilter(newX, newY, newW, newH); Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter)); BufferedImage tag = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(img, 0, 0, null); // 绘制缩小后的图 g.dispose(); return tag; }
到此,完毕。。
如果是剪切本地一个图片,然后直接切割,可以这样:
package chen.test;import java.awt.Graphics;import java.awt.Image;import java.awt.Toolkit;import java.awt.image.BufferedImage;import java.awt.image.CropImageFilter;import java.awt.image.FilteredImageSource;import java.awt.image.ImageFilter;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStream;import java.util.Date;import javax.imageio.ImageIO;import com.msp.wxcrm.model.ThdCsPrintLog;import com.msp.wxcrm.vo.query.ThdCsPrintLogQuery;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGImageEncoder;import javacommon.util.CommonUtil;import javacommon.util.Util;public class TestImg { public String cutPhoto(String photourl) throws Exception{ ThdCsPrintLog thdCsPrintLog = new ThdCsPrintLog(); thdCsPrintLog.setPhotourl(photourl); String fileRealpath = "E:/aa/upload/picmsg/153/"; System.out.println("cutPhoto..start"); String filePath = Util.getPath(this); if (CommonUtil.isNull(thdCsPrintLog.getCutpicurl())) {// 如果照片没有编辑过则获取原图片 //TODO 如果照片没有被编辑过,则 System.out.println("当前图片没有编辑过,需要剪切照片start"); String filename = thdCsPrintLog.getPhotourl() ;// 原图 String code_filepath =fileRealpath+filename; File file = new File(code_filepath); BufferedImage tphotoImg = ImageIO.read(file); // 获取图片的宽、高坐标 int oldwidth = tphotoImg.getWidth(); int oldheight = tphotoImg.getHeight(); int cutWidth=0, cutHeight=0, x=0, y=0 ; // 新的截图宽高 // 切面 if(oldwidth > oldheight){// 横图 cutHeight = oldheight; cutWidth = (int) (cutHeight*0.8566) ; x = (oldwidth-cutWidth)/2; // x=(原图宽-截图宽)/2 y= 0;// y=高 }else{// 纵图 cutWidth = oldwidth; cutHeight = (int) (cutWidth/0.8566) ; x = 0; // x= 原点 y= (oldheight-cutHeight)/2;// y=(原图高-截图高)/2; } String resultpicname = new Date().getTime()+""+CommonUtil.getRandNum(6)+"_cut.jpg"; BufferedImage cutImg = this.cutImgComput(tphotoImg, cutWidth, cutHeight, x, y, oldwidth, oldheight); File fileIn = new File(fileRealpath+resultpicname); fileIn.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(fileIn); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); encoder.encode(cutImg); cutImg.flush(); os.close(); os.flush(); System.out.println("当前图片没有编辑过,需要剪切照片end"); } System.out.println("完成。"); return filePath; } /** * 截图 * @author 路人甲 * @param image 原图 * @param width 获取面宽 * @param height 获取面高 * @param x 获取面x * @param y 获取面y * @param pagew 展示页面宽 * @param pageh 展示页面高 * @return * @throws Exception */ public BufferedImage cutImgComput(BufferedImage image, int width, int height, int x, int y, int pagew,int pageh) throws Exception{ int oldW = image.getWidth(), oldH = image.getHeight(); // 原图横纵长、宽 int newW = width * oldW/pagew; // 新宽度 = 页面截图宽 * 原图宽/展示div宽度 int newH = height * oldH/pageh; // 新高度 = 页面截图高 * 原高宽/展示div高度 int newX = x * oldW/pagew; // 新X坐标 = 选择x坐标 * 原图宽/展示div宽度 int newY = y * oldH/pageh;// 新Y坐标 = 选择y坐标 * 原高宽/展示div高度 ImageFilter cropFilter = new CropImageFilter(newX, newY, newW, newH);// ImageFilter cropFilter = new CropImageFilter(x, y, width, height); Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter)); BufferedImage tag = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(img, 0, 0, null); // 绘制缩小后的图 g.dispose(); return tag; } /** * @author 路人甲 * @date Sep 15, 20145:50:25 PM * @param args */ public static void main(String[] args) { String photourl = "153.jpg"; TestImg testImg = new TestImg(); try { testImg.cutPhoto(photourl); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
调用jquery.Jcrop.min.js 切割图片 实例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。