이 기사는 참조를 위해 Javaweb에서 이미지를 업로드하는 전체 사례를 공유합니다. 특정 내용은 다음과 같습니다
구현 아이디어
• Jcrop 플러그인을 사용하여 휴대 전화에서 그림의 좌표를 클립하십시오.
• 수집 된 매개 변수를 배경으로 전달하고 Java 그래픽 객체를 사용하여 자르기 이미지를 그리십시오.
◦ 배경 처리 흐름 :
1. 업로드 된 사진을 비례 적으로 압축하고 파일 서버에 업로드하고 로컬 임시 디렉토리에 압축 사진을 저장하십시오.
2. 압축 이미지를 페이지에 반향하고 자르기 위해 jcrop을 사용하고 전화의 좌표를 클립합니다 (X, Y, 너비, 높이)
■@paramx 대상 슬라이스 시작점 좌표 x
■@paramy 대상 슬라이스 시작점 좌표 y
■@Param Width Target Slice 너비 ■@Param Height Target Slice Height
3. 자르기 및 업로드의 백 스테이지 처리
JSP 페이지
< %@ taglib prefix = "c"uri = "http://java.sun.com/jsp/jstl/core" %> < %@ page contenttype = "text/html; charset = utf-8"언어 = "java" %> <! appletype html> <html> <head> <meta http-http-httpiv = " content = "text/html; charset = utf-8"/> <title> 사용자 아바타 </title> <link href = "$ {pagecontext.request.contextpath} /js/cutimg/css/master.css"rel = "Stylesheet"/> href = "$ {pagecontext.request.contextpath} /js/cutimg/css/upload.css"rel = "stylesheet"/> <link href = "$ {pagecontext.request.context} /js/cutimg/csss/jquery.rollbar.css" "" "" " <int <div id = "pic2"> <div id = "uploadfile"> <div style = "margin-left : 75px;"> <a href = "javaScript :;" id = "uptext"style = "color : red;"> avatar </a> </div> <p> jpg 및 png 형식 <br/> 2m 미만의 사진 </p> </div> <!-디스플레이로 돌아 가기-> <img src = ""name = "id ="instorialimg "/> </div> <pn id =" "", "" "=" "="= "= no. <a href = "JavaScript :;" 스타일 = "색상 : red"> reupload </a> </a> < /p> <입력 유형 = "hidden"name = "picval"id = "picval" /> <input type = "hidden"name = "origpicval"id = "origpicval"value = "" /> <input type = "hidden"name = "intimigpic"Id = "hidden ="hidden = "hidden" 이름 = "fileId"id = "fileId"size = "100" /> <입력 유형 = "hidden"name = "fileUrl"id = "fileUrl"size = "100" /> <입력 유형 = "hidden"name = "imgheight"id = "imgheight"size = "100" /> <input type = "hidden"name = "imgwidth" "imgwidth" </div> <div> <img id = "preview_1"src = "$ {pagecontext.request.contextpath} /images/4-3.jpg"/> </div> <p> 400 x 300 픽셀 </p> <%-<div> <img id = "preview_2" src = $ {pagecontext.request.contextpath}/images/4-3.jpg/> </div> <p> 80 x 80 픽셀-%> <p> drag 또는 Zoom 만족도 avatar </p> </div> <%-<div id = "img_description"> id = "upalert"> </font> </div> </div> </div> </div> <input type = "hidden"name = "x"id = "x"size = "5"/> <입력 유형 = "hidden"name = "w"id = "w"size = "5"/> <hidden "id ="h "size"5 "/>> <input type" 이름 = "imgurl"id = "imgurl"/> <input type = "hidden"name = "imgid"id = "imgid"/<div> <div> <div> <aveimage "> <a href ="javaScript :; " 스타일 = "색상 : 빨간색"> 아바타 저장 </a> </div> </div> </div> </div> </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"> </javascrip "> src = "$ {pagecontext.request.contextpath} /js/check.js"> </script> <scrc = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery-1.7.1.min.js"type = "text/javascript"> src = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery.form.js"type = "text/javaScript> </script> <script src ="$ {pagecontext.request.contextPath} /jquery-cutimg/jquery-cUSUT.SOPSOM-inputs.sopust.sOpust.sOpust.sOpust.sOpust.sopust.sopust.sopust.sopust.sopust.spoT.Src = "$. 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.js.js. type = "text/javaScript"> </script> <script src = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery.rollbar.min.js"type = "text/javascript"> </script> <cript src = "$ {pagecontext.request.contextpath} /js/cutimg/js/upload.ui.js"type = "text/javaScript"> </script> <script type = "text/javascript" src = "$ {pagecontext.request.contextpath} /js/dialog/dialog.js?lib=false"> </script> <script> <script type = "text/javascript"> photos.jcorpwidth = 400; // 작물 선택 상자 너비 사진. "80"]; // 이미지 크기 "너비"배열, 그림의 수에 따라 큰 그림의 너비를 크게 정의합니다. // photos.heights = [ "200", "80"]; // 이미지 크기 "High"배열, 그림 수에 따라 큰 그림의 높이를 크게 정의합니다. photos.upload_filetextid = "uptext"; // 구성 요소 버튼 텍스트 ID 사진을 업로드합니다. upload_alertid = "upalert"; // 힌트 텍스트 ID photos.upload_alertclassname = "error"; // 프롬프트 스타일의 스타일 .upload_formid = "upload_formid ="// uppload_file id photos.upload_file id photos. "OriginalImg"; // base image id photos.upload_reloadid = "up_reload"; // reupload component id photos.upload_picvalueid = "picval"; // 맨 아래 이미지 콘텐츠 id photos.upload_picfileid = "fileId"; /// upload_picfileurl을 업로드합니다. photos.upload_picimgheight = "imgheight"; // 업로드 된 기본 이미지 High Photos.upload_picimgwidth = "imgwidth"; // 업로드 된 기본 이미지 와이드 사진 .upload_temporiginValueid = "temporigpic"; // 원래 이미지 ID가 re -uploaded photos.uploaded photos. "origpicval"; // 다른 페이지가 사진을 입력 할 때 원본 이미지 내용 ID. upload_rollbarid = "pic2"; // 사용자 정의 Scrollbar id photos.upload_saveid = "saveImage"; // 이미지 저장 버튼 ID 사진 .upload_previewprefix = "preview _"; "접두사" + 번호 (1에서 시작), 예 : Id = "photos_preview1"... photos.parentFileImgid = "Imgurl"; // 부모 사진 제어 ID Photos.ParentFileValueID = "ImGID"; // 부모 사진 주소 제어 ID Photos.xid = "x"; // x photos.yid = "y"; "h"; // h photos.uptext_format = "미안, JPG, PNG 및 BMP 형식 만 시간에 맞게 지원됩니다. "/Enterprise/FilesCheck"; // address photos.url_upload = "/Enterprise/UploadPhoto? up = original"; // 이미지 업로드 기본 이미지 사진을 업로드합니다.배경 자바 코드
이미지 업로드 도구
패키지 com.shengya.service.utils; import com.shengya.service.imgcontants; import org.apache.commons.fileupload.disk.diskfileitem; import org.springframework.web.multipart.multipartfile; 가져 오기 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 javax.imageio.imagereadparam; import java.awt.*; import java.awt.geom.affinetransform; import java.awt.image.affinetransformop; import java.awt.image.bufferedimage; import java.oo java.net.urlencoder; import java.util.arraylist;/** * @author darcy * 관리자가 2016/6/17에 작성했습니다. */public class uploadUtils {// public final static string radiourl = "http://211.102.216.237:8011/fileserver/webapi/attachments/bio?"; 공개 최종 정적 문자열 Radiourl = "http://192.168.1.15:8088/fileserver/webapi/attachments/bio?"; 공개 최종 정적 문자열 URL = imgContants.img_upload + "/file/uploadimage?"; public final static string fileUrl = imgcontants.img_upload + "/file/uploadfile?"; 공개 최종 정적 문자열 vediourl = imgcontants.file_upload + "/file/uploadfile?"; 공개 최종 정적 문자열 cropurl = imgcontants.img_upload + "/file/cropimage?"; private static byte [] readasbytearr (inputStream is) {bytearRayoutputStream baos = new ByTearRayoutputStream (); try {byte [] bytes = new Byte [1024]; int 길이 = 0; while (길이 = is.read (bytes))! = -1) {baos.write (바이트, 0, 길이); } return baos.tobytearRay (); } catch (예외 e) {e.printstacktrace (); } 마침내 {try {baos.close (); } catch (ioexception e) {e.printstacktrace (); }} return null; } / ** * 이미지 업로드 * * @param 파일 * / public static string upplimage (파일)는 UnsupportedEncodingException {String filename = urlencoder.encode (file.getname (), "utf-8"); Long Filesize = file.length (); 부울 isresuffix = true; int 높이 = 0; int 너비 = 500; 문자열 mark = "t"; 문자열 모드 = "w"; String URL = sign (url) + "& channelno = muying_android" + "& filename =" + filename + "& filesize =" + filesize + "& isresuffix =" + isresuffix + "& height =" + height + "& width =" + width + "& 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 ( "범위", "bytes ="+""); // httpurlconnection의 문자 인코딩을 설정합니다. conn.setRequestProperty ( "accept-charset", "utf-8"); 아웃 스트림 = conn.getoutPutStream (); 바이트 [] buf = 새로운 바이트 [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // lencount = lencount + len; } outstream.flush (); int relpingecode = conn.getResponseCode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; } else {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; }} catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (outstream! = null) {outstream.close (); }} catch (ioexception e) {e.printstacktrace (); }} return null; } / ** * 이미지 업로드 * * @param 파일 * / public static string upplovewebimage (multipartFile 파일) 던지기 unsupportedEncodingException {String filename = urlencoder.encode (file.getoriginalFilename (), "UTF-8"); Long Filesize = file.getSize (); 부울 isresuffix = true; int 높이 = 0; int 너비 = 500; 문자열 mark = "t"; 문자열 모드 = "w"; String URL = sign (url) + "& channelno = muying_android" + "& filename =" + filename + "& filesize =" + filesize + "& isresuffix =" + isresuffix + "& height =" + height + "& width =" + width + "& 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 ( "범위", "bytes ="+""); // httpurlconnection의 문자 인코딩을 설정합니다. conn.setRequestProperty ( "accept-charset", "utf-8"); 아웃 스트림 = conn.getoutPutStream (); 바이트 [] buf = 새로운 바이트 [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // lencount = lencount + len; } outstream.flush (); int relpingecode = conn.getResponseCode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; } else {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; }} catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (outstream! = null) {outstream.close (); }} catch (ioexception e) {e.printstacktrace (); }} return null; } / ** * 비디오 업로드 * * @param 파일 * / public static string submitRadio (multipartFile 파일) 예외 {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 ( "허락-차 세트", "UTF-8"); 아웃 스트림 = conn.getoutPutStream (); 바이트 [] buf = 새로운 바이트 [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // lencount = lencount + len; } outstream.flush (); int relpingecode = conn.getResponseCode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; } else {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; }} catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (outstream! = null) {outstream.close (); }} catch (ioexception e) {e.printstacktrace (); }} return null; } /** * 이력서 스냅 샷 업로드 * * @param filename * @param content * @return * @throws UnSupportedEncodingException * /public static string upplile (문자열 파일 이름, 문자열 콘텐츠) unsupportedEncodingexception {// content = urlencoder.encode (content, "utf-8"); filename = urlencoder.encode (filename, "utf-8"); 바이트 [] contentBytes = content.getBytes (); Long Filesize = ContentBytes.length; 부울 isresuffix = true; int 높이 = 0; int 너비 = 500; 문자열 mark = "t"; 문자열 모드 = "w"; 문자열 url = sign (fileUrl) + "& channelNo = muying_android" + "& filename =" + filename + "& filesize =" + filesize + "& isresuffix =" + isresuffix + "& height =" + height + "& width =" + width + "& 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 ( "범위", "bytes ="+""); // httpurlconnection의 문자 인코딩을 설정합니다. conn.setRequestProperty ( "accept-charset", "utf-8"); 아웃 스트림 = conn.getoutPutStream (); outstream.write (contentBytes, 0, contentBytes.length); // OK Outstream.flush (); int relpingecode = conn.getResponseCode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; } else {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; }} catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (outstream! = null) {outstream.close (); }} catch (ioexception e) {e.printstacktrace (); }} return null; } / *** 첨부 업로드** @return json string* @throws UnSupportedEncodingException* / public static string (multipartFile 파일)은 UnSupportedEncodingException {String filename = urlencoder.encode (file.getoriginalfilename (), "utf-8"; Long Filesize = file.getSize (); 부울 isresuffix = true; int 높이 = 0; int 너비 = 500; 문자열 mark = "t"; 문자열 모드 = "w"; 문자열 url = sign (fileUrl) + "& channelNo = muying_android" + "& filename =" + filename + "& filesize =" + filesize + "& isresuffix =" + isresuffix + "& height =" + height + "& width =" + width + "& 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 ( "범위", "bytes ="+""); // httpurlconnection의 문자 인코딩을 설정합니다. conn.setRequestProperty ( "accept-charset", "utf-8"); 아웃 스트림 = conn.getoutPutStream (); 바이트 [] buf = 새로운 바이트 [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // lencount = lencount + len; } int relpingecode = conn.getResponseCode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; } else {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; }} catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (outstream! = null) {outstream.close (); }} catch (ioexception e) {e.printstacktrace (); }} return null; } private static string sign (String BaseUrl)은 unsupportedencodingexception {long currency = system.currenttimeMillis (); 긴 타임 스탬프 = 통화 / 1000; 문자열 data = "actionName = uploadImage" + "& secretkey = 4B19F08DBF0ADB82CE9CC7C207EC1DC9" + "& timestamp =" + timestamp; 문자열 시그니처 = hmac_sha1 ( "4b19f08dbf0adb82ccc7c207ec1dc9", urlencoder.encode (data, "utf-8")); Signature = signature.replace ( "%3D", "%3D"); Signature = signature.replace ( "%3A", "%3A"); Signature = signature.replace ( "%2f", "%2f"); BaseUrl + Data + "& Signature =" + 서명; } private static string signradio (String URL)는 예외를 {long currencybttime = system.currentTimeMillis (); 문자열 data = "secretkey = f1b79c865c424be46183a2f0a49a0f15" + "& timestamp =" + 통화; System.out.println ( "url :" + url + data); System.out.println ( "url =" + urlencoder.encode (url + data, "utf-8")); 문자열 서명 = hmacsha1util.getSignature (urlencoder.encode (url + data, "utf-8"), "f1b79c865c424be46183a2f0a49a0f15"); URL + data + "& signature =" + 서명; } private static String hmac_sha1 (문자열 키, 문자열 데이터) {String Retring = ""; try {datas = datas.replace ( "%3A", "%3A"); datas = datas.replace ( "%2f", "%2f"); datas = datas.replace ( "%3d", "%3d"); 바이트 [] data = key.getBytes ( "UTF-8"); // 주어진 바이트 배열을 기반으로 키를 구성하고 두 번째 매개 변수는 키 알고리즘의 이름을 지정합니다. SecretKey SecretKey = New SecretKeyspec (Data, "Hmacsha1"); // 지정된 MAC 알고리즘으로 MAC 객체를 생성합니다 Mac = Mac.getInstance ( "hmacsha1"); // 주어진 키 Mac.init (SecretKey)로 Mac 객체를 초기화합니다. 바이트 [] text = datas.getBytes ( "UTF-8"); // MAC 작동 완료 바이트 [] text1 = mac.dofinal (텍스트); Restring = New Base64Encoder (). EncodeBuffer (Text1); Restring = urlencoder.encode (Restring, "UTF-8"); Retring = Retring.replace ( "%0a", ""); Retring = Retring.replace ( "%0D", ""); } catch (예외 e) {e.printstacktrace (); } 리턴 리스트링; }/** * 자른 이미지 업로드 * ZXIAO 2016/09/01 * * @param fileId */public static string 제출 cutedWebimage (multipartFile 파일, 문자열 파일드, 문자열 x, String y, String h)는 지원하지 않은 {string fileId = fileId; 문자열 [] cropwidths = new String [] { "50"}; // crop 너비 // 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); // crop x coordinate int cropy = integer.parseint (y); // crop y cordinates // string [] cropfixs = new String [] { "l"}; // crop image mark set arraylist <string> listcropfix = new arraylist <string> (); ListCropfixs.add ( "l"); String SourcesUffix = "jpg"; // 기본 맵 접미사 문자열 sourcefix = ""; // 기본 맵 로고/* 부울 isresuffix = true; int 높이 = 1000; int 너비 = 750; 문자열 mark = "t"; 문자열 모드 = "w";*/ string url = sign (cropurl) + "fileId =" + fileId + "& cropwidths =" + listCropwidths + "& cropheights =" + listCropheights + "& cropx =" + cropx + "& cropy =" + cropy + "& cropfixs =" + ListCropfixs + " + ListCropfix "& 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 ( "범위", "bytes ="+""); // httpurlconnection의 문자 인코딩을 설정합니다. conn.setRequestProperty ( "accept-charset", "utf-8"); 아웃 스트림 = conn.getoutPutStream (); 바이트 [] buf = 새로운 바이트 [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // lencount = lencount + len; } int relpingecode = conn.getResponseCode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; } else {inputStream instream = conn.getInputStream (); 바이트 [] data1 = readasbytearr (instream); 문자열 json = 새 문자열 (data1); instream.close (); json 리턴; }} catch (예외 e) {e.printstacktrace (); } 마침내 {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 string submitcropimage (multipartfile 파일, 정수 x, inteer w, integer w, inteer w). folder = system.getProperty ( "java.io.tmpdir"); file tempdir = 새 파일 (폴더); // 폴더가 존재하지 않는 경우 if (! tempdir .Exists () &&! tempdir .isdir ()) {// system.out.println ( "// 존재하지 않는")을 작성하십시오. tempdir .mkdir (); } // 압축 임시 파일 문자열 srcpath = 폴더+"scaletemp.jpg"; // 파일의 접미사를 가져옵니다./*파일 uploadFile = 새 파일 (srcpath); inputStream inputStream = file.getInputStream (); FileInputStream fs = (FileInputStream) InputStream; 문자열 srcimg = urlencoder.encode (file.getoriginalFilename (), "utf-8"); 문자열 접미사 = srcimg.substring (srcimg.lastindexof ( ".")+1);*// 이미지 cutimgutils를 자르고 새로운 cutimgutils (x, y, w, h); O.SETSRCPATH (SRCPATH); O.SetSubPath (폴더+"uptemp.jpg"); 파일 tempfile = O.cut ( "jpg"); 문자열 s = 제출물 (tempfile); 반환 s; }/** * 업로드 된 이미지의 너비를 가져옵니다. BufferedImage src = null; int ret = -1; try {is = file.getInputStream (); src = javax.imageio.imageio.read (is); ret = src.getWidth (null); // 소스 이미지 너비를 가져옵니다. is.close (); } catch (예외 e) {e.printstacktrace (); } return ret; }/** * 업로드 된 이미지를 가져옵니다 * ZXIAO 2016/09/09 * @Param 파일 * @return */public static int getImgheight (multipartFile 파일) {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 (예외 e) {e.printstacktrace (); } return ret; } /*** 스케일 이미지 (높이와 폭으로 스케일링)* @param 파일 객체* @param 결과 스케일 이미지 주소* @param 높이 스케일 높이* @param width 척도 폭 거짓은 채우지 않습니다. */ public static void scale (multipartfile 파일, 문자열 결과, int 높이, int 너비, 부울 bb) {try {double ratio = 0.0; // scaling/*commonsmultipartFile cf = (CommonSmultipartFile) 파일; diskfileitem fi = (diskfileitem) cf.getfileitem (); 파일 f = fi.getStorElocation ();*/// 파일 f = 새 파일 (srcimageFile); inputStream inputStream = file.getInputStream (); bufferedImage bi = imageio.Read (inputStream); 이미지 항목 = bi.getScaledInstance (너비, 높이, bi.scale_smooth); // if ((bi.getheight ()> height) || (bi.getWidth ()> width)) {if (bi.getheight ()> bi.getWidth ()) {ratio = (new Inter (height)). doubleValue () / bi.getheight (); } else {ratio = (새 정수 (width)). doubleValue () / bi.getWidth (); } affinetransformop op = new affinetransformop (affinetransform .getScaleInstance (비율, 비율), null); 항목 = op.filter (bi, null); } if (bb) {// bufferedImage image = new bufferedImage (너비, 높이, bufferedImage.type_int_rgb); Graphics2d g = image.creategraphics (); G. 세트 컬러 (Color.white); G.FillRect (0, 0, 너비, 높이); if (width == item.getWidth (null)) g.DrawImage (itemp, 0, (높이 - item.getheight (null)) / 2, item.getWidth (null), item.getheight (null), color.white, null); else g.drawimage (itemp, (width- item.getWidth (null)) / 2, 0, item.getWidth (null), item.getheight (null), color.white, null); g.dispose (); 항목 = 이미지; } imageio.write ((bufferedImage) 항목, "jpg", 새 파일 (결과)); } catch (ioexception e) {e.printstacktrace (); }} public static void main (String [] args) {try {/* file file = new File ( "e : // bole // doc // service 인터페이스 문서 // Bole Service Interface Description v1.0.docx"); System.out.println ( "file =" + file); 문자열 JSON = 제출 파일 (파일); System.out.println ( "json =" + json);*/} catch (예외 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; java.io.fileInputStream; import java.io.ioexception; import java.util.iterator;/*** 관리자가 2016/9/1에 작성했습니다. */public class cutimgutils {// === 소스 이미지 경로 이름 : c : /1.jpg private string srcpath; // === 클립 이미지 저장 경로 이름. 예를 들면 다음과 같습니다. C : /2.JPG 개인 문자열 SUBPATH; public void setsrcpath (String srcpath) {this.srcpath = srcpath; } public void setSubpath (String subpath) {this.subpath = subpath; } // === 슬라이스 포인트 X 좌표 private int x; 개인 in y; // === 슬리프트 포인트 너비 비공개 int 너비; 개인 INT 높이; public cutimgutils () {} public cutimgutils (int x, int y, int 너비, int 높이) {if (x <0) {x = 0; } else {this.x = x; } if (y <0) {y = 0; } else {this.y = y; } this.width = 너비; this.height = 높이; } /** * * 이미지를 자르고 자르기 후 새 이미지를 저장하십시오. */ public file cut ()는 ioexception {fileInputStream is = null; imageInputStream iis = null; 시도 {// 이미지 파일 읽기는 = 새 FileInputStream (srcpath); /** * * 지정된 형식을 해독 할 수 있다고 주장하는 현재 등록 된 모든 이미지 방지기가 포함 된 반복기를 반환합니다. 매개 변수 : FormatName- 비공식 형식 이름을 포함합니다. * * (예 : "jpeg"또는 "tiff") 등 */ iterator <imageReader> it = imageio .getImagerEadersByFormatName ( "jpg"); imageReader reader = it.next (); // 이미지 스트림을 가져옵니다 IIS = imageio.createImageInputStream (is); /** * * <p> * iis : 소스를 읽으십시오. TRUE : 앞으로만 검색 * </p> *. 그것을 '앞으로만 전진'으로 표시하십시오. * *이 설정은 입력 소스에 포함 된 이미지가 순서대로 만 읽히는 것을 의미하며, 이는 독자가 이전에 읽은 이미지와 관련된 데이터를 포함하는 입력 부분을 캐시하지 않도록 할 수 있습니다. */ reader.setInput (iis, true); /** * * <p> * 스트림을 디코딩하는 방법을 설명하는 클래스 * <p> *. 입력시 Java 이미지 I/O * * 프레임 워크의 맥락에서 스트림에서 이미지 또는 이미지 세트를 변환하는 방법을 지정하는 데 사용됩니다. 특정 이미지 형식에 대한 플러그인 * * * ImageReadparam 인스턴스는 ImageReader 구현의 getDefaultReadParam 메소드에서 반환됩니다. */ imageEreadParam param = reader.getDefaLtreadParam (); /** * * 이미지 작물 영역. 사각형은 좌표 공간의 영역을 지정하며, 이는 사각형 물체 **의 좌표 (x, y), 너비 및 높이에 의해 정의 될 수 있습니다. */ 사각형 rect = 새로운 사각형 (x, y, 너비, 높이); // 픽셀 데이터를 디코딩하기위한 대상으로 사용하기 위해 BufferedImage를 제공합니다. param.setsourceregion (rect); /** * 제공된 imageEadparam을 사용하여 ImageIndex를 색인화하여 지정된 객체를 읽고 * * *를 완전한 bufferedImage로 읽습니다. */ bufferedImage bi = reader.Read (0, param); // 새 이미지 저장 imageio.write (bi, "jpg", 새 파일 (subpath)); 파일 = 새 파일 ( "subpath"); 반환 파일; } 마침내 {if (is! = null) is.close (); if (iis! = null) iis.close (); }} public file cut (문자열 접미사)은 ioexception {fileInputStream is = null; imageInputStream iis = null; 시도 {// 이미지 파일을 읽는다는 파일은 = 새 fileInputStream (srcpath); // is = inputStream; /** * 현재 등록 된 모든 이미지 방지기가 포함 된 반복자를 반환합니다. * * 지정된 형식을 해독 할 수 있다고 주장합니다. 매개 변수 : FormatName- 비공식 형식 이름을 포함합니다. * * (예 : "jpeg"또는 "tiff") 등 * ITERATOR <ImageReader> it = imageio.getImagerEadersByFormatName ( "jpg"); */ String iffixName = null; if (wiffix.equals ( "gif")) {wiffixname = "gif"; } else if (wiffix.equals ( "png")) {wiftixname = "png"; } else {wiffixname = "jpg"; } iterator <ImageReader> it = imageio .getImagerEadersByFormatName (windixName); imageReader reader = it.next (); // 이미지 스트림을 가져옵니다 IIS = imageio.createImageInputStream (is); /** * * <p> * iis : 소스를 읽으십시오. TRUE : 앞으로만 검색 * </p> *. 그것을 '앞으로만 전진'으로 표시하십시오. * *이 설정은 입력 소스에 포함 된 이미지가 순서대로 만 읽히는 것을 의미하며, 이는 독자가 이전에 읽은 이미지와 관련된 데이터를 포함하는 입력 부분을 캐시하지 않도록 할 수 있습니다. */ reader.setInput (iis, true); /** * * <p> * 스트림을 디코딩하는 방법을 설명하는 클래스 * <p> *. 입력시 Java 이미지 I/O * * 프레임 워크의 맥락에서 스트림에서 이미지 또는 이미지 세트를 변환하는 방법을 지정하는 데 사용됩니다. 특정 이미지 형식에 대한 플러그인 * * * ImageReadparam 인스턴스는 ImageReader 구현의 getDefaultReadParam 메소드에서 반환됩니다. */ imageEreadParam param = reader.getDefaLtreadParam (); /** * * 图片裁剪区域。 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(); }}}遇到的问题总结:
-裁剪图片发生偏移现象<br />解决办法:使用压缩后的图片等比例收集裁切坐标信息
-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"> <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/.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.