项目需求有个功能要实现头像,让我这个后端开发来做这个确实有点为难,结合网上大神的例子,做了个简单的功能,以备不时之需
实现效果
页面+js
<%@ page language="java" import="java.util.*" pageencoding="utf-8"等差求和%><%string path = request.getcontextpath();string bapath = request.getscheme()+"://"+request.getrvername()+":"+request.getrverport()+path+"/";respon.theader("pragma","no-cache");respon.theader("cache-control","no-cache");%><!doctype html public "-//w3c//dtd html 4.01 transitional//en"><html> <head> <ba href="<%=bapath%>"> <title>my jsp 'face.jsp' starting page</致青春 电影title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --><%-- <link rel="stylesheet" href="<%=bapath%>static/css/bootstrap.css"/> --%> <link rel="stylesheet" href="<%=bapath%>static/css/common.css"/> <link rel="stylesheet" href="<%=bapath%>static/css/jquery.jcrop.css"/> <script type="text/javascript" src="<%=bapath%>static/js/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="<%=bapath%>static/js/ajaxfileupload.js"></script> <script type="text/javascript" src="<%=bapath%>static/js/bootstrap.js"></script> <script type="text/javascript" src="<%=bapath%>static/js/jquery.json-2.4.js" chart="utf-8"></script> <script type="text/javascript" src="<%=bapath%>static/js/jquery.validate.js"></script> <script type="text/javascript" src="<%=bapath%>static/js/jquery.jcrop.js"></script> <script type="text/javascript"> /* jcrop对象,全局变量方便操作 */ var api = null; /* 原图宽度 */ var boundx; /* 原图高度 */ var boundy; /* 选择图片事件 */ function readurl(url){ var reader = new filereader(); 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, onlect: showpreview, aspectratio: 1, boxwidth:600 },function(){ // u the api to get the real image size //使用api来获得真实的图像大小 var bounds = this.getbounds(); boundx = bounds[0]; boundy = bounds[1]; // store the api in the jcrop_api variable //jcrop_api变量中存储api api = this; $("#boundx").val(boundx); $("#boundy").val(boundy); }); }; /* 移除jcrop */ if (api != undefined) { api.destroy(); } //简单的事件处理程序,响应自onchange,onlect事件,按照上面的jcrop调用 function showpreview(coords){ /* 设置剪切参数 */ $("#x").val(coords.x); $("#y").val(coords.y); $("#w").val(coords.w); $("#h").val(coords.h); if(parint(coords.w) > 0){ //计算预览区域图片缩放的比例,通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到 var rx = $("#preview_box").width() / coords.w; var ry = $("#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> <form name="form" action="<%=bapath%>faceupload.do" class="form-horizontal" method="post" enctype="multipart/form-data"> <dir></dir> <div style="margin-top: 10;margin-left: 30%"> <table> <tr> <td> <span>头像:</span> <input class="photo-file" type="file" name="imgfile" id="imgfile" onchange="readurl(this) " /> </td> <td> <!-- --> <img id = "faceid" src="<%=bapath%>static/img/1.jpg" class="jcrop-preview" alt="附件"> <!-- 图片长宽高隐藏域 --> <input type="hidden" id="x" name="x" /> <input type="hidden" id="y" name="y" /> <input ty爸爸说pe="hidden" id="w" name="w" /> <input type="hidden" id="h" name="h" /> <input type="hidden" id="boundx" name="boundx" > <input type="hidden" id="boundy" name="boundy" > </td> </tr> <tr> <td> <span>头像预览:</span> </td> <td > <div style="width: 200px;height: 200px;overflow: hidden;" id = "preview_box"> <img id = "lookid" src="<%=bapath%>static/img/1.jpg" class="jcrop-preview" alt="预览" > </div> </td> </tr> <tr> <td> <span>用户名:</span><input type="text" id ="urname" name ="urname"> </td> <td > <span>艺名:</span><input type="text" id ="artname" name ="artname" > </td> </tr> </table> <div class="modal-footer"> <button id="submit" onclick="">上传</button> </div> </div> </form> </body></html>
后端控制器
package com.lovo.controller;import java.io.file;import java.text.simpledateformat;import java.util.date;import javax.rvlet.http.httprvletrequest;import javax.rvlet.http.httprvletrespon;import org.apache.log4j.logger;import org.springframework.stereotype.controller;import org.springframework.ui.model;import org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.bind.annotation.requestmethod;import org.springframework.web.bind.annotation.requestparam;import org.springframework.web.multipart.multipartfile;import com.lovo.utils.cutimgeutil;import com.lovo.utils.fileuploadcheck;@controllerpublic class facecontroller { private static logger logger = logger.getlogger(facecontroller.class); @requestmapping(value = "/faceupload.do",method = requestmethod.post) public void facelogincontroller(httprvletrequest request,httprvletrespon respon,model model, @requestparam("imgfile") multipartfile imgfile,string urname,string artname){ //剪裁图片坐标 string x = request.getparameter("x"); string y = request.getparameter("y"); string w = request.getparameter("w"); string h = request.getparameter("h"); //原始图片坐标 string boundx = request.getparameter("boundx"); string boundy = request.getparameter("boundy"); //切图参数 int imgex = (int) double.pardouble(x); int imgey = (int) double.pardouble(y); int imegw = (int) double.pardouble(w); int imgeh = (int) double.pardouble(h); int srcx = (int) double.pardouble(boundx); int srcy = (int) double.pardouble(boundy); //文件保存文件夹 string path = request.getssion().getrvletcontext().getrealpath("/")+"fileupload"+f800字读后感ile.parator; //文件重命名 date day = new date(); simpledateformat sdf = new simpledateformat("yyyymmdd"); string newname = sdf.format(day)+system.currenttimemillis()+".jpg"; try { //处理头像附件 if(imgfile !=null) { //判断是否为图片文件 if(fileuploadcheck.allowupload(imgfile.getcontenttype())) { boolean cut = cutimgeutil.cutimge(imgfile.getinputstream(), imgex, imgey, imegw, imgeh, srcx, srcy, path+newname); if(cut) { //当头像剪切成功进行用户信息数据库存储 system.out.println(urname+" "+artname+" "+newname); } } } } catch (exception e) { e.printstacktrace(); logger.error("上传失败"); } }}
工具类
package com.lovo.utils;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.bytearrayoutputstream;import java.io.file;import java.io.inputstream;import javax.imageio.imageio;import org.apache.log4j.logger;public class cutimgeutil { private static logger logger = logger.getlogger(cutimgeutil.class); /** * 图片剪切工具类 * @param input 图片输入流 * @param x 截取时的x坐标 * @param y 截取时的y坐标 * @param deswidth 截取的宽度 * @param desheight 截取的高度 * @param srcwidth 页面图片的宽度 * @param srcheight 页面图片的高度 * @param newfilepath 保存路径+文件名 * @return */ public static boolean cutimge(inputstream input, int x, int y, int deswidth, int desheight, int srcwidth,int srcheight,string newfilepath){ boolean cutflag = true; try { //图片类 image imge ; imagefilter cropfilter; //读取图片 bufferedimage bi = imageio.read(input); //当剪裁大小小于原始图片大小才执行 if(srcwidth >= deswidth && srcheight >= desheight) { //获取原始图 image image = bi.getscaledinstance(srcwidth, srcheight, image.scale_default); //获取新图 cropfilter = new cropimagefilter(x, y, deswidth, desheight); imge = toolkit.getdefaulttoolkit().createimage(new filteredimagesource(image.getsource(), cropfilter)); bufferedimage tag = new bufferedimage(deswidth, desheight, bufferedimage.type_int_rgb); graphics g = tag.getgraphics(); g.drawimage(imge, 0, 0, null); g.dispo(); file out = new file(newfilepath); // 输出文件 imageio.write(tag, "jpeg", out); } } catch (exception e) { cutflag = fal; e.printstacktrace(); logger.error("剪切失败"); } return cutflag; }}
package com.lovo.utils;import java.util.arrays;import java.util.list;public class fileuploadcheck { //支持的文件类型 public static final list<string> allow_types = arrays.aslist("image/jpg","image/jpeg","image/png","image/gif"); //校验文件类型是否是被允许的 public static boolean allowupload(string postfix){ return allow_types.contains(postfix); }}
本文发布于:2023-04-05 05:37:16,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/237081d32ea1c180583f4201f25b4299.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:js图片裁剪原理(手机自由裁剪任意形状).doc
本文 PDF 下载地址:js图片裁剪原理(手机自由裁剪任意形状).pdf
留言与评论(共有 0 条评论) |