图像裁剪方式 影像不规则裁剪的概念
原创

图像裁剪方式 影像不规则裁剪的概念

好文
试试语音读文章

项目需求有个功能要实现头像。让我这个后端开发来做这个确实有点为难。结合网上大神的例子。做了个简单的功能。以备不时之需

实现效果

页面+js

<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";response.setHeader("Pragma","No-cache");response.setHeader("Cache-Control","no-cache");%><!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head><basehref="<%=basePath%>"><title>MyJSP'face.jsp'startingpage</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="Thisismypage"><!--<linkrel="stylesheet"type="text/css"href="styles.css">--><%--<linkrel="stylesheet"href="<%=basePath%>static/css/bootstrap.css"/>--%><linkrel="stylesheet"href="<%=basePath%>static/css/common.css"/><linkrel="stylesheet"href="<%=basePath%>static/css/jQuery.Jcrop.css"/><scripttype="text/javascript"src="<%=basePath%>static/js/jquery-1.9.1.min.js"></script><scripttype="text/javascript"src="<%=basePath%>static/js/ajaxfileupload.js"></script><scripttype="text/javascript"src="<%=basePath%>static/js/bootstrap.js"></script><scripttype="text/javascript"src="<%=basePath%>static/js/jquery.json-2.4.js"charset="UTF-8"></script><scripttype="text/javascript"src="<%=basePath%>static/js/jquery.validate.js"></script><scripttype="text/javascript"src="<%=basePath%>static/js/jquery.Jcrop.js"></script><scripttype="text/javascript">/*jcrop对象。全局变量方便操作*/varapi=null;/*原图宽度*/varboundx;/*原图高度*/varboundy;/*选择图片事件*/functionreadURL(URL){varreader=newFileReader();reader.readAsDataURL(URL.files[0]);reader.onload=function(e){$("#faceId").removeAttr("src");$("#lookId").removeAttr("src");$("#faceId").attr("src",e.target.result);$("#lookId").attr("src",e.target.result);$("#faceId").Jcrop({onChange:showPreview,onSelect:showPreview,aspectRatio:1,boxWidth:600},function(){//UsetheAPItogettherealimagesize//使用API来获得真实的图像大小varbounds=this.getBounds();boundx=bounds[0];boundy=bounds[1];//StoretheAPIinthejcrop_apivariable//jcrop_api变量中存储APIapi=this;$("#boundx").val(boundx);$("#boundy").val(boundy);});};/*移除jcrop*/if(api!=undefined){api.destroy();}//简单的事件处理程序。响应自onChange,onSelect事件。按照上面的Jcrop调用functionshowPreview(coords){/*设置剪切参数*/$("#x").val(coords.x);$("#y").val(coords.y);$("#w").val(coords.w);$("#h").val(coords.h);if(parseInt(coords.w)>0){//计算预览区域图片缩放的比例。通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到varrx=$("#preview_box").width()/coords.w;varry=$("#preview_box").height()/coords.h;$("#lookId").css({width:Math.round(rx*$("#faceId").width())+"px",//预览图片宽度为计算比例值与原图片宽度的乘积height:Math.round(rx*$("#faceId").height())+"px",//预览图片高度为计算比例值与原图片高度的乘积marginLeft:"-"+Math.round(rx*coords.x)+"px",marginTop:"-"+Math.round(ry*coords.y)+"px"});}}}</script></head><body><formname="form"action="<%=basePath%>faceUpload.do"class="form-horizontal"method="post"enctype="multipart/form-data"><dir></dir><divstyle="margin-top:10;margin-left:30%"><table><tr><td><span>头像:</span><inputclass="photo-file"type="file"name="imgFile"id="imgFile"onchange="readURL(this)"/></td><td><!----><imgid="faceId"src="<%=basePath%>static/img/1.jpg"class="jcrop-preview"alt="附件"><!--图片长宽高隐藏域--><inputtype="hidden"id="x"name="x"/><inputtype="hidden"id="y"name="y"/><inputtype="hidden"id="w"name="w"/><inputtype="hidden"id="h"name="h"/><inputtype="hidden"id="boundx"name="boundx"><inputtype="hidden"id="boundy"name="boundy"></td></tr><tr><td><span>头像预览:</span></td><td><divstyle="width:200px;height:200px;overflow:hidden;"id="preview_box"><imgid="lookId"src="<%=basePath%>static/img/1.jpg"class="jcrop-preview"alt="预览"></div></td></tr><tr><td><span>用户名:</span><inputtype="text"id="userName"name="userName"></td><td><span>艺名:</span><inputtype="text"id="artName"name="artName"></td></tr></table><divclass="modal-footer"><buttonid="submit"onclick="">上传</button></div></div></form></body></html>

后端控制器

packagecom.lovo.controller;importjava.io.File;importjava.text.SimpleDateFormat;importjava.util.Date;importjavax.servlet.http.HttpservletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.log4j.Logger;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.multipart.MultipartFile;importcom.lovo.utils.CutImgeUtil;importcom.lovo.utils.FileUploadCheck;@ControllerpublicclassFaceController{privatestaticLoggerlogger=Logger.getLogger(FaceController.class);@RequestMapping(value="/faceUpload.do",method=RequestMethod.POST)publicvoidfaceLoginController(HttpServletRequestrequest,HttpServletResponseresponse,Modelmodel,@RequestParam("imgFile")MultipartFileimgFile,StringuserName,StringartName){//剪裁图片坐标Stringx=request.getParameter("x");Stringy=request.getParameter("y");Stringw=request.getParameter("w");Stringh=request.getParameter("h");//原始图片坐标Stringboundx=request.getParameter("boundx");Stringboundy=request.getParameter("boundy");//切图参数intimgeX=(int)Double.parseDouble(x);intimgeY=(int)Double.parseDouble(y);intimegW=(int)Double.parseDouble(w);intimgeH=(int)Double.parseDouble(h);intsrcX=(int)Double.parseDouble(boundx);intsrcY=(int)Double.parseDouble(boundy);//文件保存文件夹Stringpath=request.getSession().getServletContext().getRealPath("/")+"fileUpload"+File.separator;//文件重命名Dateday=newDate();SimpleDateFormatsdf=newSimpleDateFormat("yyyyMMdd");StringnewName=sdf.format(day)+System.currentTimeMillis()+".jpg";try{//处理头像附件if(imgFile!=null){//判断是否为图片文件if(FileUploadCheck.allowUpload(imgFile.getContentType())){booleancut=CutImgeUtil.cutImge(imgFile.getInputStream(),imgeX,imgeY,imegW,imgeH,srcX,srcY,path+newName);if(cut){//当头像剪切成功进行用户信息数据库存储System.out.println(userName+""+artName+""+newName);}}}}catch(Exceptione){e.printStackTrace();logger.error("上传失败");}}}

工具类

packagecom.lovo.utils;importjava.awt.Graphics;importjava.awt.Image;importjava.awt.Toolkit;importjava.awt.image.BufferedImage;importjava.awt.image.CropImageFilter;importjava.awt.image.FilteredImageSource;importjava.awt.image.ImageFilter;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.InputStream;importjavax.imageio.ImageIO;importorg.apache.log4j.Logger;publicclassCutImgeUtil{privatestaticLoggerlogger=Logger.getLogger(CutImgeUtil.class);/***图片剪切工具类*@paraminput图片输入流*@paramx截取时的x坐标*@paramy截取时的y坐标*@paramdesWidth截取的宽度*@paramdesHeight截取的高度*@paramsrcWidth页面图片的宽度*@paramsrcHeight页面图片的高度*@paramnewFilePath保存路径+文件名*@return*/publicstaticbooleancutImge(InputStreaminput,intx,inty,intdesWidth,intdesHeight,intsrcWidth,intsrcHeight,StringnewFilePath){booleancutFlag=true;try{//图片类Imageimge;ImageFiltercropFilter;//读取图片BufferedImagebi=ImageIO.read(input);//当剪裁大小小于原始图片大小才执行if(srcWidth>=desWidth&&srcHeight>=desHeight){//获取原始图Imageimage=bi.getScaledInstance(srcWidth,srcHeight,Image.SCALE_DEFAULT);//获取新图cropFilter=newCropImageFilter(x,y,desWidth,desHeight);imge=Toolkit.getDefaultToolkit().createImage(newFilteredImageSource(image.getSource(),cropFilter));BufferedImagetag=newBufferedImage(desWidth,desHeight,BufferedImage.TYPE_INT_RGB);Graphicsg=tag.getGraphics();g.drawImage(imge,0,0,null);g.dispose();Fileout=newFile(newFilePath);//输出文件ImageIO.write(tag,"JPEG",out);}}catch(Exceptione){cutFlag=false;e.printStackTrace();logger.error("剪切失败");}returncutFlag;}}

packagecom.lovo.utils;importjava.util.Arrays;importjava.util.List;publicclassFileUploadCheck{//支持的文件类型publicstaticfinalList<String>ALLOW_TYPES=Arrays.asList("image/jpg","image/jpeg","image/png","image/gif");//校验文件类型是否是被允许的publicstaticbooleanallowUpload(Stringpostfix){returnALLOW_TYPES.contains(postfix);}}

您还感兴趣的文章推荐

以上就是由互联网推广工程师 网创网 整理编辑的,如果觉得有帮助欢迎收藏转发~

分享到 :
相关推荐

发表评论

您的电子邮箱地址不会被公开。

评论(2)

  • 夜深时 永久VIP 2022年12月14日 01:11:26

    图像裁剪方式 影像不规则裁剪的概念 这篇解答确实也是太好了

  • 风华三生 永久VIP 2022年12月14日 01:11:26

    图片,宽度,高度,头像,坐标,剪裁,文件,乘积,原图,原始

  • 浮生三叹 永久VIP 2022年12月14日 01:11:26

    项目需求有个功能要实现头像。让我这个后端开发来做这个确实有点为难。结合网上大神的例子。做了个简单的功能。以备不时之需实现