JavaWeb实现裁剪图片上传完整代码
本文实例为大家分享了JavaWeb实现裁剪图片上传完整案例,供大家参考,具体内容如下
实现思路
•使用jcrop插件手机要裁剪图片的坐标
•将收集到的参数传递到后台,在后台使用java图形对象绘制图像进行裁剪
◦后台处理流程:
1、将上传的图片按按照比例进行压缩后上传到文件服务器,并且将压缩后的图片保存在本地临时目录中。
2、将压缩后的图片回显到页面,使用jcrop进行裁剪,手机裁剪坐标(x,y,width,height)
■@paramx目标切片起点坐标X
■@paramy目标切片起点坐标Y
■@paramwidth目标切片宽度
■@paramheight目标切片高度
3、后台处理裁剪裁剪,重新上传
jsp页面
<%@taglibprefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<%@pagecontentType="text/html;charset=UTF-8"language="java"%>
<!doctypehtml>
<html>
<head>
<metahttp-equiv="content-type"content="text/html;charset=UTF-8"/>
<title>上传用户头像</title>
<linkhref="${pageContext.request.contextPath}/js/cutImg/css/master.css"rel="stylesheet"/>
<linkhref="${pageContext.request.contextPath}/js/cutImg/css/upload.css"rel="stylesheet"/>
<linkhref="${pageContext.request.contextPath}/js/cutImg/css/jquery.rollbar.css"rel="stylesheet"/>
<linkhref="${pageContext.request.contextPath}/js/cutImg/css/jquery.Jcrop.css"rel="stylesheet"/>
</head>
<body>
<divclass="user_upload">
<formid="uploadImgFrom"enctype="multipart/form-data"method="post">
<divclass="upload">
<divclass="upload_left">
<divclass="pic">
<divclass="pic2"id="pic2">
<divid="uploadFile">
<divclass="upload_btn"style="margin-left:75px;">
<ahref="javascript:;"id="upText"style="color:red;">上传头像</a>
</div>
<p>
支持jpg、png格式<br/>
图片小于2M
</p>
</div>
<!--回显示图片-->
<imgsrc=""name="photo"id="originalImg"alt=""/>
</div>
</div>
<pclass="up_reload"id="up_reload"style="display:none;">
<ahref="javascript:;"style="color:red">重新上传</a>
</p>
<inputtype="hidden"name="picval"id="picval"/>
<inputtype="hidden"name="origpicval"id="origpicval"value=""/>
<inputtype="hidden"name="temporigpic"id="temporigpic"/>
<inputtype="hidden"name="fileID"id="fileID"size="100"/>
<inputtype="hidden"name="fileUrl"id="fileUrl"size="100"/>
<inputtype="hidden"name="imgHeight"id="imgHeight"size="100"/>
<inputtype="hidden"name="imgWidth"id="imgWidth"size="100"/>
</div>
<divclass="upload_right">
<divclass="upload_view_pic"style="width:300px;height:230px;border:solid1px#ccc;overflow:hidden;">
<imgid="preview_1"src="${pageContext.request.contextPath}/images/4-3.jpg"/>
</div>
<p>
400x300像素
</p>
<%--<divclass="upload_view_pic"style="width:80px;height:80px;border:solid1px#ccc;overflow:hidden;">
<imgid="preview_2"src=${pageContext.request.contextPath}/images/4-3.jpg/>
</div>
<p>
80x80像素
</p>--%>
<p>
拖拽或缩放,生成自己满意的头像
</p>
</div>
<%--<divid="img_description">
<textarea
</div>--%>
<divclass="upload_b">
<fontid="upalert"></font>
</div>
</div>
<inputtype="hidden"name="x"id="x"size="5"/>
<inputtype="hidden"name="y"id="y"size="5"/>
<inputtype="hidden"name="w"id="w"size="5"/>
<inputtype="hidden"name="h"id="h"size="5"/>
<inputtype="hidden"name="imgUrl"id="imgUrl"/>
<inputtype="hidden"name="imgId"id="imgId"/>
<divclass="upload_submit_contain">
<divclass="upload_submit"id="saveImage">
<ahref="javascript:;"style="color:red">保存头像</a>
</div>
</div>
</form>
</div>
</body>
<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/jquery.form.js"></script>
<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/jquery.validate.min.js"></script>
<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/check.js"></script>
<scriptsrc="${pageContext.request.contextPath}/js/cutImg/js/jquery-1.7.1.min.js"type="text/javascript"></script>
<scriptsrc="${pageContext.request.contextPath}/js/cutImg/js/jquery.form.js"type="text/javascript"></script>
<scriptsrc="${pageContext.request.contextPath}/js/cutImg/js/jquery-custom-file-input.js"type="text/javascript"></script>
<scriptsrc="${pageContext.request.contextPath}/js/cutImg/js/jquery.Jcrop.js"type="text/javascript"></script>
<scriptsrc="${pageContext.request.contextPath}/js/cutImg/js/jquery.rollbar.min.js"type="text/javascript"></script>
<scriptsrc="${pageContext.request.contextPath}/js/cutImg/js/upload.ui.photos.js"type="text/javascript"></script>
<scripttype="text/javascript"src="${pageContext.request.contextPath}/js/dialog/dialog.js?lib=false"></script>
<scripttype="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代码
图片上传工具类
packagecom.shengya.service.utils;
importcom.shengya.service.ImgContants;
importorg.apache.commons.fileupload.disk.DiskFileItem;
importorg.springframework.web.multipart.MultipartFile;
importorg.springframework.web.multipart.commons.CommonsMultipartFile;
importsun.misc.BASE64Encoder;
importjavax.crypto.Mac;
importjavax.crypto.SecretKey;
importjavax.crypto.spec.SecretKeySpec;
importjavax.imageio.ImageIO;
importjavax.imageio.ImageReadParam;
importjava.awt.*;
importjava.awt.geom.AffineTransform;
importjava.awt.image.AffineTransformOp;
importjava.awt.image.BufferedImage;
importjava.io.*;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.net.URLEncoder;
importjava.util.ArrayList;
/**
*@authorDarcy
*CreatedbyAdministratoron2016/6/17.
*/
publicclassUploadUtils{
//publicfinalstaticStringRADIOURL="http://211.102.216.237:8011/fileServer/webapi/Attachments/bio?";
publicfinalstaticStringRADIOURL="http://192.168.1.15:8088/fileServer/webapi/Attachments/bio?";
publicfinalstaticStringURL=ImgContants.IMG_UPLOAD+"/file/UpLoadImage?";
publicfinalstaticStringFILEURL=ImgContants.IMG_UPLOAD+"/file/UpLoadFile?";
publicfinalstaticStringVEDIOURL=ImgContants.FILE_UPLOAD+"/file/UpLoadFile?";
publicfinalstaticStringCROPURL=ImgContants.IMG_UPLOAD+"/file/CropImage?";
privatestaticbyte[]readAsByteArr(InputStreamis){
ByteArrayOutputStreambaos=newByteArrayOutputStream();
try{
byte[]bytes=newbyte[1024];
intlength=0;
while((length=is.read(bytes))!=-1){
baos.write(bytes,0,length);
}
returnbaos.toByteArray();
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
baos.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
/**
*上传图片
*
*@paramfile
*/
publicstaticStringsubmitImage(Filefile)throwsUnsupportedEncodingException{
StringfileName=URLEncoder.encode(file.getName(),"UTF-8");
longfileSize=file.length();
booleanisReSuffix=true;
intheight=0;
intwidth=500;
Stringmark="t";
Stringmode="W";
Stringurl=sign(URL)
+"&ChannelNo=muying_android"
+"&FileName="
+fileName
+"&FileSize="
+fileSize
+"&IsReSuffix="
+isReSuffix
+"&Height="
+height
+"&Width="
+width+"&Mark="+mark+"&Mode="+mode;
System.out.println("url:"+url);
HttpURLConnectionconn=null;
OutputStreamoutStream=null;
BufferedInputStreambin=null;
try{
bin=newBufferedInputStream(newFileInputStream(file));
conn=(HttpURLConnection)newURL(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=newbyte[1024];
intlen=0;
intlenCount=0;
while((len=bin.read(buf))!=-1){
outStream.write(buf,0,len);//OK
lenCount=lenCount+len;
}
outStream.flush();
intresponseCode=conn.getResponseCode();
if(responseCode==200){
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}else{
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(outStream!=null){
outStream.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
/**
*上传图片
*
*@paramfile
*/
publicstaticStringsubmitWebImage(MultipartFilefile)throwsUnsupportedEncodingException{
StringfileName=URLEncoder.encode(file.getOriginalFilename(),"UTF-8");
longfileSize=file.getSize();
booleanisReSuffix=true;
intheight=0;
intwidth=500;
Stringmark="t";
Stringmode="W";
Stringurl=sign(URL)
+"&ChannelNo=muying_android"
+"&FileName="
+fileName
+"&FileSize="
+fileSize
+"&IsReSuffix="
+isReSuffix
+"&Height="
+height
+"&Width="
+width+"&Mark="+mark+"&Mode="+mode;
System.out.println("url:"+url);
HttpURLConnectionconn=null;
OutputStreamoutStream=null;
BufferedInputStreambin=null;
try{
bin=newBufferedInputStream(file.getInputStream());
conn=(HttpURLConnection)newURL(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=newbyte[1024];
intlen=0;
intlenCount=0;
while((len=bin.read(buf))!=-1){
outStream.write(buf,0,len);//OK
lenCount=lenCount+len;
}
outStream.flush();
intresponseCode=conn.getResponseCode();
if(responseCode==200){
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}else{
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(outStream!=null){
outStream.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
/**
*上传视频
*
*@paramfile
*/
publicstaticStringsubmitRadio(MultipartFilefile)throwsException{
Stringurl=signRadio(RADIOURL);
System.out.println("url:"+url);
HttpURLConnectionconn=null;
OutputStreamoutStream=null;
BufferedInputStreambin=null;
try{
bin=newBufferedInputStream(file.getInputStream());
conn=(HttpURLConnection)newURL(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=newbyte[1024];
intlen=0;
intlenCount=0;
while((len=bin.read(buf))!=-1){
outStream.write(buf,0,len);//OK
lenCount=lenCount+len;
}
outStream.flush();
intresponseCode=conn.getResponseCode();
if(responseCode==200){
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}else{
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(outStream!=null){
outStream.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
/**
*上传简历快照
*
*@paramfileName
*@paramcontent
*@return
*@throwsUnsupportedEncodingException
*/
publicstaticStringsubmitFile(StringfileName,Stringcontent)throwsUnsupportedEncodingException{
//content=URLEncoder.encode(content,"UTF-8");
fileName=URLEncoder.encode(fileName,"UTF-8");
byte[]contentBytes=content.getBytes();
longfileSize=contentBytes.length;
booleanisReSuffix=true;
intheight=0;
intwidth=500;
Stringmark="t";
Stringmode="W";
Stringurl=sign(FILEURL)
+"&ChannelNo=muying_android"
+"&FileName="
+fileName
+"&FileSize="
+fileSize
+"&IsReSuffix="
+isReSuffix
+"&Height="
+height
+"&Width="
+width+"&Mark="+mark+"&Mode="+mode;
System.out.println("url:"+url);
HttpURLConnectionconn=null;
OutputStreamoutStream=null;
BufferedInputStreambin=null;
try{
conn=(HttpURLConnection)newURL(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();
intresponseCode=conn.getResponseCode();
if(responseCode==200){
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}else{
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(outStream!=null){
outStream.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
/**
*上传附件
*
*@returnjson字符串
*@throwsUnsupportedEncodingException
*/
publicstaticStringsubmitFile(MultipartFilefile)throwsUnsupportedEncodingException{
StringfileName=URLEncoder.encode(file.getOriginalFilename(),"UTF-8");
longfileSize=file.getSize();
booleanisReSuffix=true;
intheight=0;
intwidth=500;
Stringmark="t";
Stringmode="W";
Stringurl=sign(FILEURL)
+"&ChannelNo=muying_android"
+"&FileName="
+fileName
+"&FileSize="
+fileSize
+"&IsReSuffix="
+isReSuffix
+"&Height="
+height
+"&Width="
+width+"&Mark="+mark+"&Mode="+mode;
System.out.println("url:"+url);
HttpURLConnectionconn=null;
OutputStreamoutStream=null;
BufferedInputStreambin=null;
try{
bin=newBufferedInputStream(file.getInputStream());
conn=(HttpURLConnection)newURL(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=newbyte[1024];
intlen=0;
intlenCount=0;
while((len=bin.read(buf))!=-1){
outStream.write(buf,0,len);//OK
lenCount=lenCount+len;
}
intresponseCode=conn.getResponseCode();
if(responseCode==200){
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}else{
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(outStream!=null){
outStream.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
privatestaticStringsign(Stringbaseurl)throwsUnsupportedEncodingException{
longcurrebttime=System.currentTimeMillis();
longtimeStamp=currebttime/1000;
Stringdata="ActionName=UpLoadImage"+"&SecretKey=4b19f08dbf0adb82ce9cc7c207ec1dc9"
+"&TimeStamp="+timeStamp;
Stringsignature=hmac_sha1("4b19f08dbf0adb82ce9cc7c207ec1dc9",
URLEncoder.encode(data,"UTF-8"));
signature=signature.replace("%3D","%3d");
signature=signature.replace("%3A","%3a");
signature=signature.replace("%2F","%2f");
returnbaseurl+data+"&Signature="+signature;
}
privatestaticStringsignRadio(Stringurl)throwsException{
longcurrebttime=System.currentTimeMillis();
Stringdata="secretKey=f1b79c865c424be46183a2f0a49a0f15"
+"&timeStamp="+currebttime;
System.out.println("url:"+url+data);
System.out.println("url="+URLEncoder.encode(url+data,"utf-8"));
Stringsignature=HmacSha1Util.getSignature(URLEncoder.encode(url+data,"utf-8"),"f1b79c865c424be46183a2f0a49a0f15");
returnurl+data+"&signature="+signature;
}
privatestaticStringhmac_sha1(Stringkey,Stringdatas){
StringreString="";
try{
datas=datas.replace("%3A","%3a");
datas=datas.replace("%2F","%2f");
datas=datas.replace("%3D","%3d");
byte[]data=key.getBytes("UTF-8");
//根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
SecretKeysecretKey=newSecretKeySpec(data,"HmacSHA1");
//生成一个指定Mac算法的Mac对象
Macmac=Mac.getInstance("HmacSHA1");
//用给定密钥初始化Mac对象
mac.init(secretKey);
byte[]text=datas.getBytes("UTF-8");
//完成Mac操作
byte[]text1=mac.doFinal(text);
reString=newBASE64Encoder().encodeBuffer(text1);
reString=URLEncoder.encode(reString,"UTF-8");
reString=reString.replace("%0A","");
reString=reString.replace("%0D","");
}catch(Exceptione){
e.printStackTrace();
}
returnreString;
}
/**
*上传裁剪图片
*zxiao2016/09/01
*
*@paramfileID
*/
publicstaticStringsubmitCutedWebImage(MultipartFilefile,StringfileID,Stringx,Stringy,Stringw,Stringh)throwsUnsupportedEncodingException{
StringFileId=fileID;
String[]CropWidths=newString[]{"50"};//裁剪宽度
//List<String>list=newList<String>();
//List<String>list=newArrayList<String>(5);
ArrayList<String>listCropWidths=newArrayList<String>();
listCropWidths.add("400");
//String[]CropHeights=newString[]{"50"};//裁剪高度
ArrayList<String>listCropHeights=newArrayList<String>();
listCropHeights.add("300");
intCropX=Integer.parseInt(x);//裁剪x坐标
intCropY=Integer.parseInt(y);//裁剪y坐标
//String[]CropFixs=newString[]{"l"};//裁剪图片的标示集合
ArrayList<String>listCropFixs=newArrayList<String>();
listCropFixs.add("l");
StringSourceSuffix="jpg";//底图后缀
StringSourceFix="";//底图标示
/*booleanisReSuffix=true;
intheight=1000;
intwidth=750;
Stringmark="t";
Stringmode="W";*/
Stringurl=sign(CROPURL)+"FileId="
+fileID
+"&CropWidths="
+listCropWidths
+"&CropHeights="
+listCropHeights
+"&CropX="
+CropX
+"&CropY="
+CropY+"&CropFixs="+listCropFixs+"&SourceSuffix="+SourceSuffix+"&SourceFix="+SourceFix;
System.out.println("url:"+url);
HttpURLConnectionconn=null;
OutputStreamoutStream=null;
BufferedInputStreambin=null;
try{
bin=newBufferedInputStream(file.getInputStream());
conn=(HttpURLConnection)newURL(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=newbyte[1024];
intlen=0;
intlenCount=0;
while((len=bin.read(buf))!=-1){
outStream.write(buf,0,len);//OK
lenCount=lenCount+len;
}
intresponseCode=conn.getResponseCode();
if(responseCode==200){
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}else{
InputStreaminStream=conn.getInputStream();
byte[]data1=readAsByteArr(inStream);
Stringjson=newString(data1);
inStream.close();
returnjson;
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(outStream!=null){
outStream.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnnull;
}
/**上传裁剪后图片需在本地保存副本
*zxiao2016/09/01
*@param,
*@paramx
*@paramy
*@paramw
*@paramh
*@return
*@throwsIOException
*/
publicstaticStringsubmitCropImage(MultipartFilefile,Integerx,Integery,Integerw,Integerh)throwsIOException{
Stringfolder=System.getProperty("java.io.tmpdir");
FiletempDir=newFile(folder);
//如果文件夹不存在则创建
if(!tempDir.exists()&&!tempDir.isDirectory())
{
//System.out.println("//不存在");
tempDir.mkdir();
}
//压缩后临时文件
StringSrcpath=folder+"scaleTemp.jpg";
//获取文件的后缀
/*FileuploadFile=newFile(Srcpath);
InputStreaminputStream=file.getInputStream();
FileInputStreamfs=(FileInputStream)inputStream;
StringsrcImg=URLEncoder.encode(file.getOriginalFilename(),"UTF-8");
Stringsuffix=srcImg.substring(srcImg.lastIndexOf(".")+1);*/
//裁剪图片
cutImgUtilso=newcutImgUtils(x,y,w,h);
o.setSrcpath(Srcpath);
o.setSubpath(folder+"uptemp.jpg");
FiletempFile=o.cut("jpg");
Strings=submitImage(tempFile);
returns;
}
/**
*获取上传图片的宽
*zxiao2016/09/09
*@paramfile
*@return
*/
publicstaticintgetImgWidth(MultipartFilefile)throwsIOException{
InputStreamis=null;
BufferedImagesrc=null;
intret=-1;
try{
is=file.getInputStream();
src=javax.imageio.ImageIO.read(is);
ret=src.getWidth(null);//得到源图宽
is.close();
}catch(Exceptione){
e.printStackTrace();
}
returnret;
}
/**
*获取上传图片的高
*zxiao2016/09/09
*@paramfile
*@return
*/
publicstaticintgetImgHeight(MultipartFilefile){
InputStreamis=null;
BufferedImagesrc=null;
intret=-1;
try{
is=file.getInputStream();
src=javax.imageio.ImageIO.read(is);
ret=src.getHeight(null);//得到源图高
is.close();
}catch(Exceptione){
e.printStackTrace();
}
returnret;
}
/**
*缩放图像(按高度和宽度缩放)
*@paramfile文件对象
*@paramresult缩放后的图像地址
*@paramheight缩放后的高度
*@paramwidth缩放后的宽度
*@parambb比例不对时是否需要补白:true为补白;false为不补白;
*/
publicstaticvoidscale(MultipartFilefile,Stringresult,intheight,intwidth,booleanbb){
try{
doubleratio=0.0;//缩放比例
/*CommonsMultipartFilecf=(CommonsMultipartFile)file;
DiskFileItemfi=(DiskFileItem)cf.getFileItem();
Filef=fi.getStoreLocation();*/
//Filef=newFile(srcImageFile);
InputStreaminputStream=file.getInputStream();
BufferedImagebi=ImageIO.read(inputStream);
Imageitemp=bi.getScaledInstance(width,height,bi.SCALE_SMOOTH);
//计算比例
if((bi.getHeight()>height)||(bi.getWidth()>width)){
if(bi.getHeight()>bi.getWidth()){
ratio=(newInteger(height)).doubleValue()
/bi.getHeight();
}else{
ratio=(newInteger(width)).doubleValue()/bi.getWidth();
}
AffineTransformOpop=newAffineTransformOp(AffineTransform
.getScaleInstance(ratio,ratio),null);
itemp=op.filter(bi,null);
}
if(bb){//补白
BufferedImageimage=newBufferedImage(width,height,
BufferedImage.TYPE_INT_RGB);
Graphics2Dg=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",newFile(result));
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
try{
/*Filefile=newFile("E:\\bole\\doc\\服务接口文档\\伯乐服务接口说明v1.0.docx");
System.out.println("file="+file);
Stringjson=submitFile(file);
System.out.println("json="+json);*/
}catch(Exceptione){
e.printStackTrace();
}
}
}
图片裁剪工具类
packagecom.shengya.service.utils;
importjavax.imageio.ImageIO;
importjavax.imageio.ImageReadParam;
importjavax.imageio.ImageReader;
importjavax.imageio.stream.ImageInputStream;
importjava.awt.*;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.util.Iterator;
/**
*CreatedbyAdministratoron2016/9/1.
*/
publicclasscutImgUtils{
//===源图片路径名称如:c:\1.jpg
privateStringsrcpath;
//===剪切图片存放路径名称。如:c:\2.jpg
privateStringsubpath;
publicvoidsetSrcpath(Stringsrcpath){
this.srcpath=srcpath;
}
publicvoidsetSubpath(Stringsubpath){
this.subpath=subpath;
}
//===剪切点x坐标
privateintx;
privateinty;
//===剪切点宽度
privateintwidth;
privateintheight;
publiccutImgUtils(){
}
publiccutImgUtils(intx,inty,intwidth,intheight){
if(x<0){
x=0;
}else{
this.x=x;
}
if(y<0){
y=0;
}else{
this.y=y;
}
this.width=width;
this.height=height;
}
/**
*
*对图片裁剪,并把裁剪完蛋新图片保存。
*/
publicFilecut()throwsIOException{
FileInputStreamis=null;
ImageInputStreamiis=null;
try{
//读取图片文件
is=newFileInputStream(srcpath);
/**
*
*返回包含所有当前已注册ImageReader的Iterator,这些ImageReader
*
*声称能够解码指定格式。参数:formatName-包含非正式格式名称.
*
*(例如"jpeg"或"tiff")等。
*/
Iterator<ImageReader>it=ImageIO
.getImageReadersByFormatName("jpg");
ImageReaderreader=it.next();
//获取图片流
iis=ImageIO.createImageInputStream(is);
/**
*
*<p>
*iis:读取源。true:只向前搜索
*</p>
*.将它标记为‘只向前搜索'。
*
*此设置意味着包含在输入源中的图像将只按顺序读取,可能允许reader
*
*避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。
*/
reader.setInput(iis,true);
/**
*
*<p>
*描述如何对流进行解码的类
*<p>
*.用于指定如何在输入时从JavaImageI/O
*
*框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件
*
*将从其ImageReader实现的getDefaultReadParam方法中返回
*
*ImageReadParam的实例。
*/
ImageReadParamparam=reader.getDefaultReadParam();
/**
*
*图片裁剪区域。Rectangle指定了坐标空间中的一个区域,通过Rectangle对象
*
*的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。
*/
Rectanglerect=newRectangle(x,y,width,height);
//提供一个BufferedImage,将其用作解码像素数据的目标。
param.setSourceRegion(rect);
/**
*
*使用所提供的ImageReadParam读取通过索引imageIndex指定的对象,并将
*
*它作为一个完整的BufferedImage返回。
*/
BufferedImagebi=reader.read(0,param);
//保存新图片
ImageIO.write(bi,"jpg",newFile(subpath));
Filefile=newFile("subpath");
returnfile;
}finally{
if(is!=null)
is.close();
if(iis!=null)
iis.close();
}
}
publicFilecut(Stringsuffix)throwsIOException{
FileInputStreamis=null;
ImageInputStreamiis=null;
try{
//读取图片文件
is=newFileInputStream(srcpath);
//is=inputStream;
/**
*
*返回包含所有当前已注册ImageReader的Iterator,这些ImageReader
*
*声称能够解码指定格式。参数:formatName-包含非正式格式名称.
*
*(例如"jpeg"或"tiff")等。
*Iterator<ImageReader>it=ImageIO.getImageReadersByFormatName("jpg");
*/
StringsuffixName=null;
if(suffix.equals("gif")){
suffixName="gif";
}elseif(suffix.equals("png")){
suffixName="png";
}else{
suffixName="jpg";
}
Iterator<ImageReader>it=ImageIO
.getImageReadersByFormatName(suffixName);
ImageReaderreader=it.next();
//获取图片流
iis=ImageIO.createImageInputStream(is);
/**
*
*<p>
*iis:读取源。true:只向前搜索
*</p>
*.将它标记为‘只向前搜索'。
*
*此设置意味着包含在输入源中的图像将只按顺序读取,可能允许reader
*
*避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。
*/
reader.setInput(iis,true);
/**
*
*<p>
*描述如何对流进行解码的类
*<p>
*.用于指定如何在输入时从JavaImageI/O
*
*框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件
*
*将从其ImageReader实现的getDefaultReadParam方法中返回
*
*ImageReadParam的实例。
*/
ImageReadParamparam=reader.getDefaultReadParam();
/**
*
*图片裁剪区域。Rectangle指定了坐标空间中的一个区域,通过Rectangle对象
*
*的左上顶点的坐标(x,y)、宽度和高度可以定义这个区域。
*/
Rectanglerect=newRectangle(x,y,width,height);
//提供一个BufferedImage,将其用作解码像素数据的目标。
param.setSourceRegion(rect);
/**
*
*使用所提供的ImageReadParam读取通过索引imageIndex指定的对象,并将
*
*它作为一个完整的BufferedImage返回。
*/
BufferedImagebi=reader.read(0,param);
//保存新图片
ImageIO.write(bi,"jpg",newFile(subpath));
Filefile=newFile(subpath);
returnfile;
}finally{
if(is!=null)
is.close();
if(iis!=null)
iis.close();
}
}
}
遇到的问题总结:
-裁剪图片发生偏移现象
解决办法:使用压缩后的图片等比例收集裁切坐标信息
-MultipartFile和File之间相互转化
第一种方法:
MultipartFilefile=xxx; CommonsMultipartFilecf=(CommonsMultipartFile)file; DiskFileItemfi=(DiskFileItem)cf.getFileItem(); Filef=fi.getStoreLocation();
会在项目的根目录的临时文件夹下生成一个文件;
第二种方法:
transferTo(Filedest);
会在项目中生成一个新文件;
第三种方法:
Filef=(File)xxx强转即可。前提是要配置multipartResolver,要不然会报类型转换失败的异常。
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <propertyname="maxUploadSize"value="104857600"/> <propertyname="maxInMemorySize"value="4096"/> </bean>
没试过;
第四种方法:
Workbookwb=Workbook.getWorkbook(xxx.getInputStream());
转换为输入流,直接读取;
第五种方法:
byte[]buffer=myfile.getBytes();
先转换为字节数组,没试过;
第六种方法:
直接转成输入流
MultipartFilefile=xxx; is=file.getInputStream(); src=javax.imageio.ImageIO.read(is); ret=src.getWidth(null);//得到源图宽
参考资料:
jcopapi:http://code.ciaoca.com/jquery/jcrop/.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。