JavaWeb實(shí)現(xiàn)裁剪圖片上傳完整代碼
本文實(shí)例為大家分享了JavaWeb實(shí)現(xiàn)裁剪圖片上傳完整案例,供大家參考,具體內(nèi)容如下
實(shí)現(xiàn)思路
•使用jcrop插件手機(jī)要裁剪圖片的坐標(biāo)
•將收集到的參數(shù)傳遞到后臺(tái),在后臺(tái)使用java圖形對(duì)象繪制圖像進(jìn)行裁剪
◦后臺(tái)處理流程:
1、將上傳的圖片按按照比例進(jìn)行壓縮后上傳到文件服務(wù)器,并且將壓縮后的圖片保存在本地臨時(shí)目錄中。
2、將壓縮后的圖片回顯到頁面,使用jcrop進(jìn)行裁剪,手機(jī)裁剪坐標(biāo)(x,y,width,height)
■@paramx 目標(biāo)切片起點(diǎn)坐標(biāo)X
■@param y 目標(biāo)切片起點(diǎn)坐標(biāo)Y
■@param width 目標(biāo)切片寬度
■@param height 目標(biāo)切片高度
3、后臺(tái)處理裁剪裁剪,重新上傳
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;//裁剪選擇框?qū)挾? photos.JcorpHeight = 300;//裁剪框選擇高度 // photos.Widths = ["200", "80"];// 圖片大小“寬”數(shù)組,根據(jù)圖片張數(shù)由大到小定義不同圖片的寬度 // photos.Heights = ["200", "80"];// 圖片大小“高”數(shù)組,根據(jù)圖片張數(shù)由大到小定義不同圖片的高度 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";//上傳的底圖片內(nèi)容ID photos.UpLoad_PicFileID = "fileID";////上傳圖片id photos.UpLoad_PicFileUrl = "fileUrl";////上傳圖片url photos.UpLoad_PicImgHeight="imgHeight";//上傳的底圖高 photos.UpLoad_PicImgWidth="imgWidth";//上傳的底圖寬 photos.UpLoad_TempOriginValueID = "temporigpic";//本頁面重新上傳時(shí)的原圖片內(nèi)容ID photos.UpLoad_OriginValueID = "origpicval";//其他頁面進(jìn)入時(shí)的原圖片內(nèi)容ID photos.Upload_RollbarID = "pic2";//自定義滾動(dòng)條ID photos.UpLoad_SaveID = "saveImage";//圖片保存按鈕ID photos.UpLoad_PreviewPreFix = "preview_";//多個(gè)不同尺寸小圖的ID前綴名稱,多個(gè)小圖ID格式“前綴”+數(shù)字編號(hào)(從1開始),例:id="photos_preview1" ... photos.ParentFileImgID = "imgUrl";//父級(jí)圖片控件ID photos.ParentFileValueID = "imgId";//父級(jí)圖片地址控件ID photos.XID = "x";//x photos.YID = "y";//y photos.WID = "w";//w photos.HID = "h";//h photos.UpText_Format = "抱歉,暫只支持 jpg、png、bmp 格式";//圖片格式驗(yàn)證文本 /* photos.UpText_Size = "抱歉,圖片大小不能超過2M";*///圖片大小驗(yàn)證文本 /*photos.UpText_Error = "圖片上傳出錯(cuò)";//上傳出錯(cuò)文本*/ photos.Url_Check = "/Enterprise/filescheck";//文件驗(yàn)證大小的地址 photos.Url_UpLoad = "/Enterprise/uploadphoto?up=original";//上傳圖片載入底圖的地址 photos.Url_ReLoad = "";//重新上傳的地址 photos.Url_Save = "/Enterprise/saveimg?up=save";//保存圖片的地址 </script> </html>
后臺(tái)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="+""); // 設(shè)置 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="+""); // 設(shè)置 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="+""); // 設(shè)置 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="+""); // 設(shè)置 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" + "&TimeStamp=" + 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" + "&timeStamp=" + 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"); // 根據(jù)給定的字節(jié)數(shù)組構(gòu)造一個(gè)密鑰,第二參數(shù)指定一個(gè)密鑰算法的名稱 SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1"); // 生成一個(gè)指定 Mac 算法 的 Mac 對(duì)象 Mac mac = Mac.getInstance("HmacSHA1"); // 用給定密鑰初始化 Mac 對(duì)象 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坐標(biāo) int CropY=Integer.parseInt(y);//裁剪y坐標(biāo) // String[] CropFixs=new String[]{"l"};//裁剪圖片的標(biāo)示集合 ArrayList<String> listCropFixs = new ArrayList<String>(); listCropFixs.add("l"); String SourceSuffix="jpg";//底圖后綴 String SourceFix="";//底圖標(biāo)示 /* 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="+""); // 設(shè)置 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); //如果文件夾不存在則創(chuàng)建 if (!tempDir .exists() && !tempDir .isDirectory()) { // System.out.println("http://不存在"); tempDir .mkdir(); } //壓縮后臨時(shí)文件 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 文件對(duì)象 * @param result 縮放后的圖像地址 * @param height 縮放后的高度 * @param width 縮放后的寬度 * @param bb 比例不對(duì)時(shí)是否需要補(bǔ)白:true為補(bǔ)白; false為不補(bǔ)白; */ 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); // 計(jì)算比例 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) {//補(bǔ)白 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\\服務(wù)接口文檔\\伯樂服務(wù)接口說明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; } // ===剪切點(diǎn)x坐標(biāo) private int x; private int y; // ===剪切點(diǎn)寬度 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; } /** * * 對(duì)圖片裁剪,并把裁剪完蛋新圖片保存 。 */ public File cut() throws IOException { FileInputStream is = null; ImageInputStream iis = null; try { // 讀取圖片文件 is = new FileInputStream(srcpath); /** * * 返回包含所有當(dāng)前已注冊(cè) ImageReader 的 Iterator,這些 ImageReader * * 聲稱能夠解碼指定格式。 參數(shù):formatName - 包含非正式格式名稱 . * * (例如 "jpeg" 或 "tiff")等 。 */ Iterator<ImageReader> it = ImageIO .getImageReadersByFormatName("jpg"); ImageReader reader = it.next(); // 獲取圖片流 iis = ImageIO.createImageInputStream(is); /** * * <p> * iis:讀取源。true:只向前搜索 * </p> * .將它標(biāo)記為 ‘只向前搜索'。 * * 此設(shè)置意味著包含在輸入源中的圖像將只按順序讀取,可能允許 reader * * 避免緩存包含與以前已經(jīng)讀取的圖像關(guān)聯(lián)的數(shù)據(jù)的那些輸入部分。 */ reader.setInput(iis, true); /** * * <p> * 描述如何對(duì)流進(jìn)行解碼的類 * <p> * .用于指定如何在輸入時(shí)從 Java Image I/O * * 框架的上下文中的流轉(zhuǎn)換一幅圖像或一組圖像。用于特定圖像格式的插件 * * 將從其 ImageReader 實(shí)現(xiàn)的 getDefaultReadParam 方法中返回 * * ImageReadParam 的實(shí)例。 */ ImageReadParam param = reader.getDefaultReadParam(); /** * * 圖片裁剪區(qū)域。Rectangle 指定了坐標(biāo)空間中的一個(gè)區(qū)域,通過 Rectangle 對(duì)象 * * 的左上頂點(diǎn)的坐標(biāo)(x,y)、寬度和高度可以定義這個(gè)區(qū)域。 */ Rectangle rect = new Rectangle(x, y, width, height); // 提供一個(gè) BufferedImage,將其用作解碼像素?cái)?shù)據(jù)的目標(biāo)。 param.setSourceRegion(rect); /** * * 使用所提供的 ImageReadParam 讀取通過索引 imageIndex 指定的對(duì)象,并將 * * 它作為一個(gè)完整的 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; /** * * 返回包含所有當(dāng)前已注冊(cè) ImageReader 的 Iterator,這些 ImageReader * * 聲稱能夠解碼指定格式。 參數(shù):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> * .將它標(biāo)記為 ‘只向前搜索'。 * * 此設(shè)置意味著包含在輸入源中的圖像將只按順序讀取,可能允許 reader * * 避免緩存包含與以前已經(jīng)讀取的圖像關(guān)聯(lián)的數(shù)據(jù)的那些輸入部分。 */ reader.setInput(iis, true); /** * * <p> * 描述如何對(duì)流進(jìn)行解碼的類 * <p> * .用于指定如何在輸入時(shí)從 Java Image I/O * * 框架的上下文中的流轉(zhuǎn)換一幅圖像或一組圖像。用于特定圖像格式的插件 * * 將從其 ImageReader 實(shí)現(xiàn)的 getDefaultReadParam 方法中返回 * * ImageReadParam 的實(shí)例。 */ ImageReadParam param = reader.getDefaultReadParam(); /** * * 圖片裁剪區(qū)域。Rectangle 指定了坐標(biāo)空間中的一個(gè)區(qū)域,通過 Rectangle 對(duì)象 * * 的左上頂點(diǎn)的坐標(biāo)(x,y)、寬度和高度可以定義這個(gè)區(qū)域。 */ Rectangle rect = new Rectangle(x, y, width, height); // 提供一個(gè) BufferedImage,將其用作解碼像素?cái)?shù)據(jù)的目標(biāo)。 param.setSourceRegion(rect); /** * * 使用所提供的 ImageReadParam 讀取通過索引 imageIndex 指定的對(duì)象,并將 * * 它作為一個(gè)完整的 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(); } } }
遇到的問題總結(jié):
-裁剪圖片發(fā)生偏移現(xiàn)象
解決辦法:使用壓縮后的圖片等比例收集裁切坐標(biāo)信息
-MultipartFile 和 File之間相互轉(zhuǎn)化
第一種方法:
MultipartFile file = xxx; CommonsMultipartFile cf= (CommonsMultipartFile)file; DiskFileItem fi = (DiskFileItem)cf.getFileItem(); File f = fi.getStoreLocation();
會(huì)在項(xiàng)目的根目錄的臨時(shí)文件夾下生成一個(gè)文件;
第二種方法:
transferTo(File dest);
會(huì)在項(xiàng)目中生成一個(gè)新文件;
第三種方法:
File f = (File) xxx 強(qiáng)轉(zhuǎn)即可。前提是要配置multipartResolver,要不然會(huì)報(bào)類型轉(zhuǎn)換失敗的異常?! ?/p>
<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());
轉(zhuǎn)換為輸入流,直接讀??;
第五種方法:
byte[] buffer = myfile.getBytes();
先轉(zhuǎn)換為字節(jié)數(shù)組,沒試過;
第六種方法:
直接轉(zhuǎn)成輸入流
MultipartFile file=xxx; is = file.getInputStream(); src = javax.imageio.ImageIO.read(is); ret = src.getWidth(null); // 得到源圖寬
參考資料:
jcop api:http://code.ciaoca.com/jquery/jcrop/.
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java實(shí)現(xiàn)圖片上傳到服務(wù)器并把上傳的圖片讀取出來
- java web圖片上傳和文件上傳實(shí)例
- java通過模擬post方式提交表單實(shí)現(xiàn)圖片上傳功能實(shí)例
- Java以struts2為例介紹如何實(shí)現(xiàn)圖片上傳
- Java圖片上傳實(shí)現(xiàn)代碼
- java使用CKEditor實(shí)現(xiàn)圖片上傳功能
- Java實(shí)現(xiàn)的圖片上傳工具類完整實(shí)例
- 微信 java 實(shí)現(xiàn)js-sdk 圖片上傳下載完整流程
- Java+mysql本地圖片上傳數(shù)據(jù)庫及下載示例
- java實(shí)現(xiàn)多圖片上傳功能
相關(guān)文章
Java實(shí)現(xiàn)批量修改txt文件名稱的方法示例
這篇文章主要介紹了Java實(shí)現(xiàn)批量修改txt文件名稱的方法,結(jié)合實(shí)例形式分析了Java針對(duì)目錄文件遍歷及文件讀寫、屬性操作等相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2019-03-03springboot斷言異常封裝與統(tǒng)一異常處理實(shí)現(xiàn)代碼
異常處理其實(shí)一直都是項(xiàng)目開發(fā)中的大頭,但關(guān)注異常處理的人一直都特別少,下面這篇文章主要給大家介紹了關(guān)于springboot斷言異常封裝與統(tǒng)一異常處理的相關(guān)資料,需要的朋友可以參考下2023-01-01Java 遞歸遍歷實(shí)現(xiàn)linux tree命令方式
這篇文章主要介紹了Java 遞歸遍歷實(shí)現(xiàn)linux tree命令方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09Java獲取服務(wù)器IP及端口的方法實(shí)例分析
這篇文章主要介紹了Java獲取服務(wù)器IP及端口的方法,結(jié)合實(shí)例形式分析了java針對(duì)客戶端及服務(wù)器端各種常見的信息操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-12-12如何將Spring Session存儲(chǔ)到Redis中實(shí)現(xiàn)持久化
這篇文章主要介紹了如何將Spring Session存儲(chǔ)到Redis中實(shí)現(xiàn)持久化,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07