JavaWeb实现裁剪图片上传完整代码
本文实例为大家分享了javaweb实现裁剪图片上传完整案例,供大家参考,具体内容如下
实现思路
•使用jcrop插件手机要裁剪图片的坐标
•将收集到的参数传递到后台,在后台使用java图形对象绘制图像进行裁剪
◦后台处理流程:
1、将上传的图片按按照比例进行压缩后上传到文件服务器,并且将压缩后的图片保存在本地临时目录中。
2、将压缩后的图片回显到页面,使用jcrop进行裁剪,手机裁剪坐标(x,y,width,height)
■@paramx 目标切片起点坐标x
■@param y 目标切片起点坐标y
■@param width 目标切片宽度
■@param height 目标切片高度
3、后台处理裁剪裁剪,重新上传
jsp页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page contenttype="text/html;charset=utf-8" language="java" %> <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>上传用户头像</title> <link href="${pagecontext.request.contextpath}/js/cutimg/css/master.css" rel="stylesheet" /> <link href="${pagecontext.request.contextpath}/js/cutimg/css/upload.css" rel="stylesheet" /> <link href="${pagecontext.request.contextpath}/js/cutimg/css/jquery.rollbar.css" rel="stylesheet" /> <link href="${pagecontext.request.contextpath}/js/cutimg/css/jquery.jcrop.css" rel="stylesheet" /> </head> <body> <div class="user_upload"> <form id="uploadimgfrom" enctype="multipart/form-data" method="post"> <div class="upload"> <div class="upload_left"> <div class="pic"> <div class="pic2" id="pic2" > <div id="uploadfile"> <div class="upload_btn" style="margin-left: 75px;"> <a href="javascript:;" id="uptext" style="color:red;">上传头像</a> </div> <p> 支持jpg、png格式<br /> 图片小于2m </p> </div> <!--回显示图片--> <img src="" name="photo" id="originalimg" alt=""/> </div> </div> <p class="up_reload" id="up_reload" style="display: none;"> <a href="javascript:;" style="color: red">重新上传</a> </p> <input type="hidden" name="picval" id="picval" /> <input type="hidden" name="origpicval" id="origpicval" value="" /> <input type="hidden" name="temporigpic" id="temporigpic" /> <input type="hidden" name="fileid" id="fileid" size="100" /> <input type="hidden" name="fileurl" id="fileurl" size="100" /> <input type="hidden" name="imgheight" id="imgheight" size="100" /> <input type="hidden" name="imgwidth" id="imgwidth" size="100" /> </div> <div class="upload_right"> <div class="upload_view_pic" style="width: 300px; height: 230px; border: solid 1px #ccc; overflow: hidden;"> <img id="preview_1" src="${pagecontext.request.contextpath}/images/4-3.jpg"/> </div> <p> 400 x 300像素 </p> <%--<div class="upload_view_pic" style="width: 80px; height: 80px; border: solid 1px #ccc; overflow: hidden;"> <img id="preview_2" src=${pagecontext.request.contextpath}/images/4-3.jpg /> </div> <p> 80 x 80像素 </p>--%> <p> 拖拽或缩放,生成自己满意的头像 </p> </div> <%-- <div id="img_description"> <textarea </div>--%> <div class="upload_b"> <font id="upalert"></font> </div> </div> <input type="hidden" name="x" id="x" size="5" /> <input type="hidden" name="y" id="y" size="5" /> <input type="hidden" name="w" id="w" size="5" /> <input type="hidden" name="h" id="h" size="5" /> <input type="hidden" name="imgurl" id="imgurl"/> <input type="hidden" name="imgid" id="imgid"/> <div class="upload_submit_contain"> <div class="upload_submit" id="saveimage"> <a href="javascript:;" style="color: red">保存头像</a> </div> </div> </form> </div> </body> <script type="text/javascript" src="${pagecontext.request.contextpath}/js/jquery.form.js"></script> <script type="text/javascript" src="${pagecontext.request.contextpath}/js/jquery.validate.min.js"></script> <script type="text/javascript" src="${pagecontext.request.contextpath}/js/check.js"></script> <script src="${pagecontext.request.contextpath}/js/cutimg/js/jquery-1.7.1.min.js" type="text/javascript"></script> <script src="${pagecontext.request.contextpath}/js/cutimg/js/jquery.form.js" type="text/javascript"></script> <script src="${pagecontext.request.contextpath}/js/cutimg/js/jquery-custom-file-input.js" type="text/javascript"></script> <script src="${pagecontext.request.contextpath}/js/cutimg/js/jquery.jcrop.js" type="text/javascript"></script> <script src="${pagecontext.request.contextpath}/js/cutimg/js/jquery.rollbar.min.js" type="text/javascript"></script> <script src="${pagecontext.request.contextpath}/js/cutimg/js/upload.ui.photos.js" type="text/javascript"></script> <script type="text/javascript" src="${pagecontext.request.contextpath}/js/dialog/dialog.js?lib=false"></script> <script type="text/javascript"> photos.jcorpwidth = 400;//裁剪选择框宽度 photos.jcorpheight = 300;//裁剪框选择高度 // photos.widths = ["200", "80"];// 图片大小“宽”数组,根据图片张数由大到小定义不同图片的宽度 // photos.heights = ["200", "80"];// 图片大小“高”数组,根据图片张数由大到小定义不同图片的高度 photos.upload_fileid = "uploadfile";//上传组件属性id photos.upload_filetextid = "uptext";//上传组件按钮文本id photos.upload_alertid = "upalert";//提示文本id photos.upload_alertclassname = "error";//提示文本增加的样式 photos.upload_formid = "uploadimgfrom";//上传组件表单id photos.upload_originfileid = "originalimg";//底图图片id photos.upload_reloadid = "up_reload";//重新上传组件id photos.upload_picvalueid = "picval";//上传的底图片内容id photos.upload_picfileid = "fileid";////上传图片id photos.upload_picfileurl = "fileurl";////上传图片url photos.upload_picimgheight="imgheight";//上传的底图高 photos.upload_picimgwidth="imgwidth";//上传的底图宽 photos.upload_temporiginvalueid = "temporigpic";//本页面重新上传时的原图片内容id photos.upload_originvalueid = "origpicval";//其他页面进入时的原图片内容id photos.upload_rollbarid = "pic2";//自定义滚动条id photos.upload_saveid = "saveimage";//图片保存按钮id photos.upload_previewprefix = "preview_";//多个不同尺寸小图的id前缀名称,多个小图id格式“前缀”+数字编号(从1开始),例:id="photos_preview1" ... photos.parentfileimgid = "imgurl";//父级图片控件id photos.parentfilevalueid = "imgid";//父级图片地址控件id photos.xid = "x";//x photos.yid = "y";//y photos.wid = "w";//w photos.hid = "h";//h photos.uptext_format = "抱歉,暂只支持 jpg、png、bmp 格式";//图片格式验证文本 /* photos.uptext_size = "抱歉,图片大小不能超过2m";*///图片大小验证文本 /*photos.uptext_error = "图片上传出错";//上传出错文本*/ photos.url_check = "/enterprise/filescheck";//文件验证大小的地址 photos.url_upload = "/enterprise/uploadphoto?up=original";//上传图片载入底图的地址 photos.url_reload = "";//重新上传的地址 photos.url_save = "/enterprise/saveimg?up=save";//保存图片的地址 </script> </html>
后台java代码
图片上传工具类
package com.shengya.service.utils; import com.shengya.service.imgcontants; import org.apache.commons.fileupload.disk.diskfileitem; import org.springframework.web.multipart.multipartfile; import org.springframework.web.multipart.commons.commonsmultipartfile; import sun.misc.base64encoder; import javax.crypto.mac; import javax.crypto.secretkey; import javax.crypto.spec.secretkeyspec; import javax.imageio.imageio; import javax.imageio.imagereadparam; import java.awt.*; import java.awt.geom.affinetransform; import java.awt.image.affinetransformop; import java.awt.image.bufferedimage; import java.io.*; import java.net.httpurlconnection; import java.net.url; import java.net.urlencoder; import java.util.arraylist; /** * @author darcy * created by administrator on 2016/6/17. */ public class uploadutils { // public final static string radiourl = "http://211.102.216.237:8011/fileserver/webapi/attachments/bio?"; public final static string radiourl = "http://192.168.1.15:8088/fileserver/webapi/attachments/bio?"; public final static string url = imgcontants.img_upload + "/file/uploadimage?"; public final static string fileurl = imgcontants.img_upload + "/file/uploadfile?"; public final static string vediourl = imgcontants.file_upload + "/file/uploadfile?"; public final static string cropurl = imgcontants.img_upload + "/file/cropimage?"; private static byte[] readasbytearr(inputstream is) { bytearrayoutputstream baos = new bytearrayoutputstream(); try { byte[] bytes = new byte[1024]; int length = 0; while ((length = is.read(bytes)) != -1) { baos.write(bytes, 0, length); } return baos.tobytearray(); } catch (exception e) { e.printstacktrace(); } finally { try { baos.close(); } catch (ioexception e) { e.printstacktrace(); } } return null; } /** * 上传图片 * * @param file */ public static string submitimage(file file) throws unsupportedencodingexception { string filename = urlencoder.encode(file.getname(), "utf-8"); long filesize = file.length(); boolean isresuffix = true; int height = 0; int width = 500; string mark = "t"; string mode = "w"; string url = sign(url) + "&channelno=muying_android" + "&filename=" + filename + "&filesize=" + filesize + "&isresuffix=" + isresuffix + "&height=" + height + "&width=" + width + "&mark=" + mark + "&mode=" + mode; system.out.println("url:" + url); httpurlconnection conn = null; outputstream outstream = null; bufferedinputstream bin = null; try { bin = new bufferedinputstream(new fileinputstream(file)); conn = (httpurlconnection) new url(url) .openconnection(); conn.setconnecttimeout(15000); conn.setrequestmethod("post"); conn.setdooutput(true); // conn.setfixedlengthstreamingmode(file.length()); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty("content-length", file.length() + ""); // conn.setrequestproperty("range", "bytes="+""); // 设置 httpurlconnection的字符编码 conn.setrequestproperty("accept-charset", "utf-8"); outstream = conn.getoutputstream(); byte[] buf = new byte[1024]; int len = 0; int lencount = 0; while ((len = bin.read(buf)) != -1) { outstream.write(buf, 0, len);//ok lencount = lencount + len; } outstream.flush(); int responsecode = conn.getresponsecode(); if (responsecode == 200) { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } else { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } } catch (exception e) { e.printstacktrace(); } finally { try { if (outstream != null) { outstream.close(); } } catch (ioexception e) { e.printstacktrace(); } } return null; } /** * 上传图片 * * @param file */ public static string submitwebimage(multipartfile file) throws unsupportedencodingexception { string filename = urlencoder.encode(file.getoriginalfilename(), "utf-8"); long filesize = file.getsize(); boolean isresuffix = true; int height = 0; int width = 500; string mark = "t"; string mode = "w"; string url = sign(url) + "&channelno=muying_android" + "&filename=" + filename + "&filesize=" + filesize + "&isresuffix=" + isresuffix + "&height=" + height + "&width=" + width + "&mark=" + mark + "&mode=" + mode; system.out.println("url:" + url); httpurlconnection conn = null; outputstream outstream = null; bufferedinputstream bin = null; try { bin = new bufferedinputstream(file.getinputstream()); conn = (httpurlconnection) new url(url) .openconnection(); conn.setconnecttimeout(15000); conn.setrequestmethod("post"); conn.setdooutput(true); // conn.setfixedlengthstreamingmode(file.length()); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty("content-length", file.getsize() + ""); // conn.setrequestproperty("range", "bytes="+""); // 设置 httpurlconnection的字符编码 conn.setrequestproperty("accept-charset", "utf-8"); outstream = conn.getoutputstream(); byte[] buf = new byte[1024]; int len = 0; int lencount = 0; while ((len = bin.read(buf)) != -1) { outstream.write(buf, 0, len);//ok lencount = lencount + len; } outstream.flush(); int responsecode = conn.getresponsecode(); if (responsecode == 200) { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } else { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } } catch (exception e) { e.printstacktrace(); } finally { try { if (outstream != null) { outstream.close(); } } catch (ioexception e) { e.printstacktrace(); } } return null; } /** * 上传视频 * * @param file */ public static string submitradio(multipartfile file) throws exception { string url = signradio(radiourl); system.out.println("url:" + url); httpurlconnection conn = null; outputstream outstream = null; bufferedinputstream bin = null; try { bin = new bufferedinputstream(file.getinputstream()); conn = (httpurlconnection) new url(url) .openconnection(); conn.setconnecttimeout(15000); conn.setrequestmethod("post"); conn.setdooutput(true); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty("content-length", file.getsize() + ""); conn.setrequestproperty("accept-charset", "utf-8"); outstream = conn.getoutputstream(); byte[] buf = new byte[1024]; int len = 0; int lencount = 0; while ((len = bin.read(buf)) != -1) { outstream.write(buf, 0, len);//ok lencount = lencount + len; } outstream.flush(); int responsecode = conn.getresponsecode(); if (responsecode == 200) { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } else { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } } catch (exception e) { e.printstacktrace(); } finally { try { if (outstream != null) { outstream.close(); } } catch (ioexception e) { e.printstacktrace(); } } return null; } /** * 上传简历快照 * * @param filename * @param content * @return * @throws unsupportedencodingexception */ public static string submitfile(string filename, string content) throws unsupportedencodingexception { //content = urlencoder.encode(content, "utf-8"); filename = urlencoder.encode(filename, "utf-8"); byte[] contentbytes = content.getbytes(); long filesize = contentbytes.length; boolean isresuffix = true; int height = 0; int width = 500; string mark = "t"; string mode = "w"; string url = sign(fileurl) + "&channelno=muying_android" + "&filename=" + filename + "&filesize=" + filesize + "&isresuffix=" + isresuffix + "&height=" + height + "&width=" + width + "&mark=" + mark + "&mode=" + mode; system.out.println("url:" + url); httpurlconnection conn = null; outputstream outstream = null; bufferedinputstream bin = null; try { conn = (httpurlconnection) new url(url) .openconnection(); conn.setconnecttimeout(15000); conn.setrequestmethod("post"); conn.setdooutput(true); // conn.setfixedlengthstreamingmode(file.length()); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty("content-length", content.length() + ""); // conn.setrequestproperty("range", "bytes="+""); // 设置 httpurlconnection的字符编码 conn.setrequestproperty("accept-charset", "utf-8"); outstream = conn.getoutputstream(); outstream.write(contentbytes, 0, contentbytes.length);//ok outstream.flush(); int responsecode = conn.getresponsecode(); if (responsecode == 200) { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } else { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } } catch (exception e) { e.printstacktrace(); } finally { try { if (outstream != null) { outstream.close(); } } catch (ioexception e) { e.printstacktrace(); } } return null; } /** * 上传附件 * * @return json 字符串 * @throws unsupportedencodingexception */ public static string submitfile(multipartfile file) throws unsupportedencodingexception { string filename = urlencoder.encode(file.getoriginalfilename(), "utf-8"); long filesize = file.getsize(); boolean isresuffix = true; int height = 0; int width = 500; string mark = "t"; string mode = "w"; string url = sign(fileurl) + "&channelno=muying_android" + "&filename=" + filename + "&filesize=" + filesize + "&isresuffix=" + isresuffix + "&height=" + height + "&width=" + width + "&mark=" + mark + "&mode=" + mode; system.out.println("url:" + url); httpurlconnection conn = null; outputstream outstream = null; bufferedinputstream bin = null; try { bin = new bufferedinputstream(file.getinputstream()); conn = (httpurlconnection) new url(url) .openconnection(); conn.setconnecttimeout(15000); conn.setrequestmethod("post"); conn.setdooutput(true); // conn.setfixedlengthstreamingmode(file.length()); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty("content-length", file.getsize() + ""); // conn.setrequestproperty("range", "bytes="+""); // 设置 httpurlconnection的字符编码 conn.setrequestproperty("accept-charset", "utf-8"); outstream = conn.getoutputstream(); byte[] buf = new byte[1024]; int len = 0; int lencount = 0; while ((len = bin.read(buf)) != -1) { outstream.write(buf, 0, len);//ok lencount = lencount + len; } int responsecode = conn.getresponsecode(); if (responsecode == 200) { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } else { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } } catch (exception e) { e.printstacktrace(); } finally { try { if (outstream != null) { outstream.close(); } } catch (ioexception e) { e.printstacktrace(); } } return null; } private static string sign(string baseurl) throws unsupportedencodingexception { long currebttime = system.currenttimemillis(); long timestamp = currebttime / 1000; string data = "actionname=uploadimage" + "&secretkey=4b19f08dbf0adb82ce9cc7c207ec1dc9" + "×tamp=" + timestamp; string signature = hmac_sha1("4b19f08dbf0adb82ce9cc7c207ec1dc9", urlencoder.encode(data, "utf-8")); signature = signature.replace("%3d", "%3d"); signature = signature.replace("%3a", "%3a"); signature = signature.replace("%2f", "%2f"); return baseurl + data + "&signature=" + signature; } private static string signradio(string url) throws exception { long currebttime = system.currenttimemillis(); string data = "secretkey=f1b79c865c424be46183a2f0a49a0f15" + "×tamp=" + currebttime; system.out.println("url:" + url + data); system.out.println("url = " + urlencoder.encode(url + data, "utf-8")); string signature = hmacsha1util.getsignature(urlencoder.encode(url + data, "utf-8"), "f1b79c865c424be46183a2f0a49a0f15"); return url + data + "&signature=" + signature; } private static string hmac_sha1(string key, string datas) { string restring = ""; try { datas = datas.replace("%3a", "%3a"); datas = datas.replace("%2f", "%2f"); datas = datas.replace("%3d", "%3d"); byte[] data = key.getbytes("utf-8"); // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称 secretkey secretkey = new secretkeyspec(data, "hmacsha1"); // 生成一个指定 mac 算法 的 mac 对象 mac mac = mac.getinstance("hmacsha1"); // 用给定密钥初始化 mac 对象 mac.init(secretkey); byte[] text = datas.getbytes("utf-8"); // 完成 mac 操作 byte[] text1 = mac.dofinal(text); restring = new base64encoder().encodebuffer(text1); restring = urlencoder.encode(restring, "utf-8"); restring = restring.replace("%0a", ""); restring = restring.replace("%0d", ""); } catch (exception e) { e.printstacktrace(); } return restring; } /** * 上传裁剪图片 * zxiao 2016/09/01 * * @param fileid */ public static string submitcutedwebimage(multipartfile file,string fileid,string x,string y,string w,string h) throws unsupportedencodingexception { string fileid=fileid; string[] cropwidths=new string[]{"50"};//裁剪宽度 //list<string> list=new list<string>(); //list<string> list = new arraylist<string>(5); arraylist<string> listcropwidths = new arraylist<string>(); listcropwidths.add("400"); // string[] cropheights=new string[]{"50"};//裁剪高度 arraylist<string> listcropheights = new arraylist<string>(); listcropheights.add("300"); int cropx=integer.parseint(x);//裁剪x坐标 int cropy=integer.parseint(y);//裁剪y坐标 // string[] cropfixs=new string[]{"l"};//裁剪图片的标示集合 arraylist<string> listcropfixs = new arraylist<string>(); listcropfixs.add("l"); string sourcesuffix="jpg";//底图后缀 string sourcefix="";//底图标示 /* boolean isresuffix = true; int height = 1000; int width = 750; string mark = "t"; string mode = "w";*/ string url = sign(cropurl) + "fileid=" + fileid + "&cropwidths=" + listcropwidths + "&cropheights=" + listcropheights + "&cropx=" + cropx + "&cropy=" + cropy + "&cropfixs=" + listcropfixs + "&sourcesuffix=" + sourcesuffix+ "&sourcefix=" + sourcefix; system.out.println("url:" + url); httpurlconnection conn = null; outputstream outstream = null; bufferedinputstream bin = null; try { bin = new bufferedinputstream(file.getinputstream()); conn = (httpurlconnection) new url(url) .openconnection(); conn.setconnecttimeout(15000); conn.setrequestmethod("post"); conn.setdooutput(true); // conn.setfixedlengthstreamingmode(file.length()); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty("content-length", file.getsize() + ""); // conn.setrequestproperty("range", "bytes="+""); // 设置 httpurlconnection的字符编码 conn.setrequestproperty("accept-charset", "utf-8"); outstream = conn.getoutputstream(); byte[] buf = new byte[1024]; int len = 0; int lencount = 0; while ((len = bin.read(buf)) != -1) { outstream.write(buf, 0, len);//ok lencount = lencount + len; } int responsecode = conn.getresponsecode(); if (responsecode == 200) { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } else { inputstream instream = conn.getinputstream(); byte[] data1 = readasbytearr(instream); string json = new string(data1); instream.close(); return json; } } catch (exception e) { e.printstacktrace(); } finally { try { if (outstream != null) { outstream.close(); } } catch (ioexception e) { e.printstacktrace(); } } return null; } /**上传裁剪后图片 需在本地保存副本 *zxiao 2016/09/01 * @param , * @param x * @param y * @param w * @param h * @return * @throws ioexception */ public static string submitcropimage(multipartfile file,integer x,integer y,integer w,integer h) throws ioexception { string folder=system.getproperty("java.io.tmpdir"); file tempdir =new file(folder); //如果文件夹不存在则创建 if (!tempdir .exists() && !tempdir .isdirectory()) { // system.out.println("//不存在"); tempdir .mkdir(); } //压缩后临时文件 string srcpath=folder+"scaletemp.jpg"; //获取文件的后缀 /*file uploadfile = new file(srcpath); inputstream inputstream = file.getinputstream(); fileinputstream fs= (fileinputstream) inputstream; string srcimg = urlencoder.encode(file.getoriginalfilename(), "utf-8"); string suffix=srcimg.substring(srcimg.lastindexof(".")+1);*/ //裁剪图片 cutimgutils o = new cutimgutils(x,y,w,h); o.setsrcpath(srcpath); o.setsubpath(folder+"uptemp.jpg"); file tempfile = o.cut("jpg"); string s = submitimage(tempfile); return s; } /** * 获取上传图片的宽 * zxiao 2016/09/09 * @param file * @return */ public static int getimgwidth(multipartfile file) throws ioexception { inputstream is = null; bufferedimage src = null; int ret = -1; try { is = file.getinputstream(); src = javax.imageio.imageio.read(is); ret = src.getwidth(null); // 得到源图宽 is.close(); } catch (exception e) { e.printstacktrace(); } return ret; } /** * 获取上传图片的高 * zxiao 2016/09/09 * @param file * @return */ public static int getimgheight(multipartfile file) { inputstream is = null; bufferedimage src = null; int ret = -1; try { is = file.getinputstream(); src = javax.imageio.imageio.read(is); ret = src.getheight(null); // 得到源图高 is.close(); } catch (exception e) { e.printstacktrace(); } return ret; } /** * 缩放图像(按高度和宽度缩放) * @param file 文件对象 * @param result 缩放后的图像地址 * @param height 缩放后的高度 * @param width 缩放后的宽度 * @param bb 比例不对时是否需要补白:true为补白; false为不补白; */ public static void scale(multipartfile file, string result, int height, int width, boolean bb) { try { double ratio = 0.0; // 缩放比例 /*commonsmultipartfile cf= (commonsmultipartfile)file; diskfileitem fi = (diskfileitem)cf.getfileitem(); file f = fi.getstorelocation();*/ // file f = new file(srcimagefile); inputstream inputstream = file.getinputstream(); bufferedimage bi = imageio.read(inputstream); image itemp = bi.getscaledinstance(width, height, bi.scale_smooth); // 计算比例 if ((bi.getheight() > height) || (bi.getwidth() > width)) { if (bi.getheight() > bi.getwidth()) { ratio = (new integer(height)).doublevalue() / bi.getheight(); } else { ratio = (new integer(width)).doublevalue() / bi.getwidth(); } affinetransformop op = new affinetransformop(affinetransform .getscaleinstance(ratio, ratio), null); itemp = op.filter(bi, null); } if (bb) {//补白 bufferedimage image = new bufferedimage(width, height, bufferedimage.type_int_rgb); graphics2d g = image.creategraphics(); g.setcolor(color.white); g.fillrect(0, 0, width, height); if (width == itemp.getwidth(null)) g.drawimage(itemp, 0, (height - itemp.getheight(null)) / 2, itemp.getwidth(null), itemp.getheight(null), color.white, null); else g.drawimage(itemp, (width - itemp.getwidth(null)) / 2, 0, itemp.getwidth(null), itemp.getheight(null), color.white, null); g.dispose(); itemp = image; } imageio.write((bufferedimage) itemp, "jpg", new file(result)); } catch (ioexception e) { e.printstacktrace(); } } public static void main(string[] args) { try { /* file file = new file("e:\\bole\\doc\\服务接口文档\\伯乐服务接口说明v1.0.docx"); system.out.println("file = " + file); string json = submitfile(file); system.out.println("json = " + json);*/ } catch (exception e) { e.printstacktrace(); } } }
图片裁剪工具类
package com.shengya.service.utils; import javax.imageio.imageio; import javax.imageio.imagereadparam; import javax.imageio.imagereader; import javax.imageio.stream.imageinputstream; import java.awt.*; import java.awt.image.bufferedimage; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.util.iterator; /** * created by administrator on 2016/9/1. */ public class cutimgutils { // ===源图片路径名称如:c:\1.jpg private string srcpath; // ===剪切图片存放路径名称。如:c:\2.jpg private string subpath; public void setsrcpath(string srcpath) { this.srcpath = srcpath; } public void setsubpath(string subpath) { this.subpath = subpath; } // ===剪切点x坐标 private int x; private int y; // ===剪切点宽度 private int width; private int height; public cutimgutils() { } public cutimgutils(int x, int y, int width, int height) { if(x<0){ x=0; }else{ this.x = x; } if(y<0){ y=0; }else{ this.y = y; } this.width = width; this.height = height; } /** * * 对图片裁剪,并把裁剪完蛋新图片保存 。 */ public file cut() throws ioexception { fileinputstream is = null; imageinputstream iis = null; try { // 读取图片文件 is = new fileinputstream(srcpath); /** * * 返回包含所有当前已注册 imagereader 的 iterator,这些 imagereader * * 声称能够解码指定格式。 参数:formatname - 包含非正式格式名称 . * * (例如 "jpeg" 或 "tiff")等 。 */ iterator<imagereader> it = imageio .getimagereadersbyformatname("jpg"); imagereader reader = it.next(); // 获取图片流 iis = imageio.createimageinputstream(is); /** * * <p> * iis:读取源。true:只向前搜索 * </p> * .将它标记为 ‘只向前搜索'。 * * 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 reader * * 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。 */ reader.setinput(iis, true); /** * * <p> * 描述如何对流进行解码的类 * <p> * .用于指定如何在输入时从 java image i/o * * 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 * * 将从其 imagereader 实现的 getdefaultreadparam 方法中返回 * * imagereadparam 的实例。 */ imagereadparam param = reader.getdefaultreadparam(); /** * * 图片裁剪区域。rectangle 指定了坐标空间中的一个区域,通过 rectangle 对象 * * 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。 */ rectangle rect = new rectangle(x, y, width, height); // 提供一个 bufferedimage,将其用作解码像素数据的目标。 param.setsourceregion(rect); /** * * 使用所提供的 imagereadparam 读取通过索引 imageindex 指定的对象,并将 * * 它作为一个完整的 bufferedimage 返回。 */ bufferedimage bi = reader.read(0, param); // 保存新图片 imageio.write(bi, "jpg", new file(subpath)); file file = new file("subpath"); return file; } finally { if (is != null) is.close(); if (iis != null) iis.close(); } } public file cut(string suffix) throws ioexception { fileinputstream is = null; imageinputstream iis = null; try { // 读取图片文件 is = new fileinputstream(srcpath); // is = inputstream; /** * * 返回包含所有当前已注册 imagereader 的 iterator,这些 imagereader * * 声称能够解码指定格式。 参数:formatname - 包含非正式格式名称 . * * (例如 "jpeg" 或 "tiff")等 。 * iterator<imagereader> it = imageio.getimagereadersbyformatname("jpg"); */ string suffixname=null; if(suffix.equals("gif")){ suffixname="gif"; }else if(suffix.equals("png")){ suffixname="png"; } else{ suffixname="jpg"; } iterator<imagereader> it = imageio .getimagereadersbyformatname(suffixname); imagereader reader = it.next(); // 获取图片流 iis = imageio.createimageinputstream(is); /** * * <p> * iis:读取源。true:只向前搜索 * </p> * .将它标记为 ‘只向前搜索'。 * * 此设置意味着包含在输入源中的图像将只按顺序读取,可能允许 reader * * 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。 */ reader.setinput(iis, true); /** * * <p> * 描述如何对流进行解码的类 * <p> * .用于指定如何在输入时从 java image i/o * * 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 * * 将从其 imagereader 实现的 getdefaultreadparam 方法中返回 * * imagereadparam 的实例。 */ imagereadparam param = reader.getdefaultreadparam(); /** * * 图片裁剪区域。rectangle 指定了坐标空间中的一个区域,通过 rectangle 对象 * * 的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。 */ rectangle rect = new rectangle(x, y, width, height); // 提供一个 bufferedimage,将其用作解码像素数据的目标。 param.setsourceregion(rect); /** * * 使用所提供的 imagereadparam 读取通过索引 imageindex 指定的对象,并将 * * 它作为一个完整的 bufferedimage 返回。 */ bufferedimage bi = reader.read(0, param); // 保存新图片 imageio.write(bi, "jpg", new file(subpath)); file file = new file(subpath); return file; } finally { if (is != null) is.close(); if (iis != null) iis.close(); } } }
遇到的问题总结:
-裁剪图片发生偏移现象
解决办法:使用压缩后的图片等比例收集裁切坐标信息
-multipartfile 和 file之间相互转化
第一种方法:
multipartfile file = xxx; commonsmultipartfile cf= (commonsmultipartfile)file; diskfileitem fi = (diskfileitem)cf.getfileitem(); file f = fi.getstorelocation();
会在项目的根目录的临时文件夹下生成一个文件;
第二种方法:
transferto(file dest);
会在项目中生成一个新文件;
第三种方法:
file f = (file) xxx 强转即可。前提是要配置multipartresolver,要不然会报类型转换失败的异常。
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> <property name="maxuploadsize" value="104857600"/> <property name="maxinmemorysize" value="4096"/> </bean>
没试过;
第四种方法:
workbook wb = workbook.getworkbook(xxx .getinputstream());
转换为输入流,直接读取;
第五种方法:
byte[] buffer = myfile.getbytes();
先转换为字节数组,没试过;
第六种方法:
直接转成输入流
multipartfile file=xxx; is = file.getinputstream(); src = javax.imageio.imageio.read(is); ret = src.getwidth(null); // 得到源图宽
参考资料:
jcop api:http://code.ciaoca.com/jquery/jcrop/.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: 第一个Jsf程序