この記事では、参照のためにJavawebの画像をアップロードする完全なケースを共有しています。特定のコンテンツは次のとおりです
実装のアイデア
•JCROPプラグインを使用して、携帯電話の画像の座標をクリップします
•収集したパラメーターを背景に渡すには、Javaグラフィックオブジェクトを使用して、トリミング用の画像を描画します
◦バックグラウンド処理フロー:
1.アップロードされた画像を比例して圧縮し、ファイルサーバーにアップロードし、ローカルの一時ディレクトリに圧縮画像を保存します。
2。圧縮された画像をページにエコーし、JCROPを使用してトリミングに使用し、電話で座標をクリップします(x、y、幅、高さ)
■@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"言語= " content = "text/html; charset = utf-8"/> <title> uploadユーザーAvatar </title> <link href = "$ {pagecontext.contextpath} /js/cutimg/css/master.css" rel = "styleSheet"/> <リンク< href = "$ {pagecontext.request.contextpath} /js/cutimg/css/upload.css" rel = "styleSheet"/> <link href = "$ {pagecontext.request.contextpath} /js/cutimg/cs/jquery.rullbar. <link href = "$ {pagecontext.request.contextpath} /js/cutimg/css/jquery.jcrop.css" rel = "styleSheet"/>> </head> <body> <div> <form id = "uploadimgfrom" enctype = "multipart/formipart <div> <div id = "pic2"> <div id = "uploadfile"> <div style = "marve-left:75px;"> <a href = "javascript :;" id = "uptext" style = "color:red;"> avatar </a> </div> <p> support jpg and pngフォーマット</p> </div> <! - 表示するために戻る</p> </div> <! - > <img src = "" name = "photo" id = "style ="/div div div div div <> <p> <p> <p> <p> <p> <p> <p> </div> <p>なし; "> <a href =" javascript :; " style = "color:red"> re upload </a> < /p> <input Type = "hidden" name = "picval" id = "picval" /> <input Type = "hidden" name = "origpicval" id = "origpicval" value = "" />> <inputタイプ= "非表示" name = "fileid" "fileid" "" />> <input typic "" fileid "" fileid ""ファイルsize = "100" /> <入力タイプ= "hidden" name = "fileurl" id = "fileurl" size = "100" /> <input type = "hidden" name = "imgheight" id = "imgheight" size = "100" /> <入力タイプ= "hidden" name = "imgwidth" id = "imgwidth" size = "100" /> < /<> <> src = "$ {pagecontext.request.contextpath}/images/4-3.jpg"/> </div> <p> 400 x 300 pixels </p> <% - <div> <img id = "preperiew_2" src = $ {pagecontext.request.contextpateピクセル</p> - %> <p>ドラッグまたはズームに満足のいくアバターを生成する</p> </div> <% - <div id = "img_description"> <textarea </div> - %> <div> <font id = "upalert"> </font> </div> div "x" x "x" x "x" x "/div>" "x" x "/div>" "x" x "x" x "x" x "x" x "x" x "x <入力タイプ= "hidden" name = "w" id = "w" size = "5" /> <input type = "hidden" name = "h" id = "h" size = "5" /> <input型= "hidden" name = "imgurl" id = "imgurl" /> <inputタイプ= "hidden" name = "imgid" = "imgid" href = "javascript :;" style = "color:red"> avatar </a> </div> </div> </form> </div> </body> <スクリプトタイプ= "text/javascript" src = "$ {pagecontext.request.context. src = "$ {pagecontext.request.contextpath} /js/jquery.validate.min.js"> </script> <script = "text/javascript" src = "$ {pagecontext.request.request.contextpath} /js/check.js src = "$ {pagecontext.request.contextpath} /js/check.js"> </script> <script src = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery-1.7.1.min.js src = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery.form.js" type = "> javascript"> javascript "> javascript> <script src =" $ {pagecontext.request.request.contextpath} type = "text/javascript"> </script> <script src = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery-custom-file-input.js" type = "text/javascript"> </script> <スクリプトsrc = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery.jcrop.js" type = "text/javascript"> </script> <scrip = "$ {pagecontext.request.request.contextpath} type = "text/javascript"> </script> <script src = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery.rollbar.min.js" type = "text/javascript"> </script> <スクリプトsrc = "$ {pagecontext.request.contextpath} /js/cutimg/js/upload.ui.photos.js" type = "text/javascript"> </scrip> <script = "text/javascript" src = "$ {pagecontext.request.contextpath} /js/dialog/dialog.js?lib = false"> </script> <script type = "text/javascript"> photos.jcorpwidth = 400; //クロップ選択ボックス幅写真「80」]; photos.upload_filetextid = "uptext"; //アップロードコンポーネントボタンテキストID写真photos.upload_alertid = "upalert"; // hint text id photos.upload_alertclassname = "error"; //プロンプトのテキストのスタイル写真。 "originalimg"; // base image id photos.upload_reloadid = "up_reload"; // reupload component id photos.upload_picvalueid = "picval"; //ボトム画像コンテンツid photos.upload_picfileid = "fileid"; // "fileurl"; ///画像のアップロードurl photos.upload_picimgheight = "imgheight"; //アップロードされたベース画像ハイ写真。 photos.upload_originvalueid = "origpicval"; //他のページがphotos.upload_rollbarid = "pic2"; // custom scrollbar id photos.upload_saveid = "saveimage"; //画像保存ボタンID写真。さまざまなサイズ、複数の小さな写真「プレフィックス」 +番号(1から始まる)のID形式、例:id = "photos_preview1" ... photos.parentfileimgid = "imgurl"; //親の写真制御ID写真。 "w"; // w photos.hid = "h"; // h photos.uptext_format = "申し訳ありませんが、jpg、png、およびbmp形式のみが当面がサポートされています"; photos.url_check = "/empertise/filescheck"; //アドレスphotos.url_upload = "/enterprise/uploadphoto?up = original"; //アップロード画像のロードベース画像写真photos.url_reload = ";背景Javaコード
画像アップロードツール
パッケージcom.shengya.service.utils; Import com.shengya.service.imgcontants; Import org.apache.commons.fileupload.diskfileitem; Import org.springframework.web.multipart.multipartfile; Import; wab.multipart.commons.commonsmultipartfile; Import sun.misc.base64encoder; Import javax.crypto.mac; import javax.crypto.secretkey; import javax.crypto.spec.seretkeyspec; Import javax.imageioiio javax.imageio.imagereadparam; Import java.awt。*; import java.awt.geom.affinetransform; Import java.awt.affinetransformop; Import java.awt.image.bufferedimage; Import java.io 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?"; 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(); {byte [] bytes = new byte [1024]; int length = 0; while((length = is.read(bytes))!= -1){baos.write(bytes、0、length); } baos.tobytearray()を返します。 } catch(Exception e){e.printstacktrace(); }最後に{try {baos.close(); } catch(ioexception e){e.printstacktrace(); }} nullを返します。 } / ** *アップロード画像 * * @param file * / public static string submitimage(file file)shrows unsupportedencodingception {string filename = urlencoder.encode(file.getName()、 "utf-8"); long filesize = file.length(); boolean isResuffix = true; int height = 0; int width = 500;文字列マーク= "t";文字列モード= "w"; string url = sign(url) + "&channelno = muying_android" + "&filename =" + filename + "&filenize =" + filesize + "&isResuffix =" + isResuffix + "&height +"&width = " + width +"&mark = " + mark +"&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 resspecode = conn.getResponseCode(); if(responsecode == 200){inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 } else {inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 }} catch(例外e){e.printstacktrace(); }最後に{try {if(outstream!= null){outstream.close(); }} catch(ioexception e){e.printstacktrace(); }} nullを返します。 } / ** * Image * * @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;文字列マーク= "t";文字列モード= "w"; string url = sign(url) + "&channelno = muying_android" + "&filename =" + filename + "&filenize =" + filesize + "&isResuffix =" + isResuffix + "&height +"&width = " + width +"&mark = " + mark +"&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 resspecode = conn.getResponseCode(); if(responsecode == 200){inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 } else {inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 }} catch(例外e){e.printstacktrace(); }最後に{try {if(outstream!= null){outstream.close(); }} catch(ioexception e){e.printstacktrace(); }} nullを返します。 } / ** * upload video * * @param file * / 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( "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 resspecode = conn.getResponseCode(); if(responsecode == 200){inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 } else {inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 }} catch(例外e){e.printstacktrace(); }最後に{try {if(outstream!= null){outstream.close(); }} catch(ioexception e){e.printstacktrace(); }} nullを返します。 } /** * resume snapshot * * @param filename * @param content * @return * @throws unsupportedencodingexception * /public static string submitfile(string filename、string content)suplows 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;文字列マーク= "t";文字列モード= "w"; string url = sign(fileurl) + "&channelno = muying_android" + "&filename =" + filename + "&filenize =" + filesize + "&isResuffix =" + isResuffix + "&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 resspecode = conn.getResponseCode(); if(responsecode == 200){inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 } else {inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 }} catch(例外e){e.printstacktrace(); }最後に{try {if(outstream!= null){outstream.close(); }} catch(ioexception e){e.printstacktrace(); }} nullを返します。 } / ***添付ファイルのアップロード** @return json string* @throws unsupportedencodingception* / public static string submitfile(multipartfile file)slows unsupportedencodingception {string filename = urlencoder.encode(file.getoriginalfilename()、 "utf-8"); long filesize = file.getSize(); boolean isResuffix = true; int height = 0; int width = 500;文字列マーク= "t";文字列モード= "w"; string url = sign(fileurl) + "&channelno = muying_android" + "&filename =" + filename + "&filenize =" + filesize + "&isResuffix =" + isResuffix + "&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 resspecode = conn.getResponseCode(); if(responsecode == 200){inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 } else {inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 }} catch(例外e){e.printstacktrace(); }最後に{try {if(outstream!= null){outstream.close(); }} catch(ioexception e){e.printstacktrace(); }} nullを返します。 } private static string sign(string baseurl)unsupportedencodingexception {long currency = system.currenttimemillis(); long timestamp = currency / 1000; string data = "ActionName = uploadImage" + "&secretkey = 4b19f08dbf0adb82ce9cc7c207ec1dc9" + "&timestamp =" + timestamp;文字列署名= hmac_sha1( "4b19f08dbf0adb82ce9cc7c207ec1dc9"、urlencoder.encode(data、 "utf-8")); signature = signature.replace( "%3d"、 "%3d"); signature = signature.replace( "%3a"、 "%3a"); signature = signature.replace( "%2f"、 "%2f"); baseurl + data + "&signature =" + signature; } private static string signradio(string url)exception {long currencybttime = system.currenttimemillis();文字列data = "secretkey = f1b79c865c424bbe46183a2f0a49a0f15" + "&timestamp =" + currency; System.out.println( "url:" + url + data); System.out.println( "url =" + urlencoder.encode(url + data、 "utf-8"));文字列署名= hmacsha1util.getsignature(urlencoder.encode(url + data、 "utf-8")、 "f1b79c865c424bbe46183a2f0a49a0f15"); return url + data + "&signature =" + signature; } private static string hmac_sha1(string key、string datas){string reting = ""; try {datas = datas.replace( "%3a"、 "%3a"); Datas = datas.replace( "%2f"、 "%2f"); Datas = datas.Replace( "%3D"、 "%3D"); byte [] data = key.getBytes( "utf-8"); //指定されたバイト配列に基づいてキーを作成し、2番目のパラメーターはキーアルゴリズムの名前を指定しましたsecretkey secretkey = new SecretKeyspec(data、 "hmacsha1"); //指定されたMacアルゴリズムでMacオブジェクトを生成するMac = mac.getInstance( "hmacsha1"); //指定されたキーmac.init(secretkey)でMacオブジェクトを初期化します。 byte [] text = datas.getBytes( "utf-8"); //完全なMac操作byte [] text1 = mac.dofinal(text); RESTRING = new Base64Encoder()。encodeBuffer(text1); stristing = urlencoder.encode(restring、 "utf-8"); RESTRING = RESTRING.REPLACE( "%0A"、 ""); RESTRING = RESTRING.REPLACE( "%0D"、 ""); } catch(Exception e){e.printstacktrace(); } Return Restring; }/** * Cropped Image * Zxiao 2016/09/01 * * @param fileid */public static string submittedCutedWebimage(MultiPartFileID、String X、String Y、String W、String H)Strows UnsupportedencodingExcection {string fileid = fileid; string [] cropwidths = new String [] {"50"}; // crop width // 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"}; // Crop Height ArrayList <String> listCropheights = new ArrayList <String>(); listcropheights.add( "300"); int cropx = integer.parseint(x); //トリミングx座標int cropy = integer.parseint(y); // coardinates // string [] cropfixs = new String [] {"l"}; //画像マークセットset arraylist <string> listcropfixs = new ArrayList <String>(); listcropfixs.add( "l"); String sourceSuffix = "jpg"; //ベースマップサフィックス文字列sourcefix = ""; //ベースマップlogo/* boolean isResuffix = true; int height = 1000; int width = 750;文字列マーク= "t"; string mode = "w";*/ string url = sign(cropurl) + "fileid =" + fileid + "&listcropwidths +"&cropheights = " + listcropheights +"&cropx = " + cropx +"&cropy = " + cropy +"&cropfixs = " + listcropfixs +" + " +" + "&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 resspecode = conn.getResponseCode(); if(responsecode == 200){inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 } else {inputstream instream = conn.getInputStream(); byte [] data1 = readasbytearr(instream);文字列json = new String(data1); instream.close(); jsonを返します。 }} catch(例外e){e.printstacktrace(); }最後に{try {if(outstream!= null){outstream.close(); }} catch(ioexception e){e.printstacktrace(); }} nullを返します。 }/**アップロードとトリミング後に画像をローカルに保存する必要があります * zxiao 2016/09/01 * @param、 * @param x * @param y * @param w * @param h * @return */public static string submitcropimage(Multipartfile file、Integer X、Integer Y、Integer Y、Integer Y string folder = system.getProperty( "java.io.tmpdir");ファイルtempdir = new file(folder); //フォルダーが存在しない場合、if(!tempdir .exists()&&!tempdir .isdir()){// system.out.println( "// exists"); tempdir .mkdir(); } //圧縮された一時ファイル文字列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);*//画像のトリミングo = new cutimgutils(x、y、w、h); o.setsrcpath(srcpath); o.setsubpath(folder+"uptemp.jpg"); file tempfile = o.cut( "jpg");文字列s = submitimage(tempfile); 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); //ソース画像幅を取得します。close(); } catch(Exception e){e.printstacktrace(); } rett; }/** *アップロードされた画像を高く入手 * 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); //ソース画像の高さを取得します。close(); } catch(Exception e){e.printstacktrace(); } rett; } /***スケール画像(高さと幅によるスケーリング)* @paramファイルオブジェクト* @param結果の画像アドレス* @param height scale height* @param widthスケール幅* @param bbスケールが間違っている場合に記入する必要があります。 Falseは記入されていません。 */ public static voidスケール(multipartfileファイル、文字列結果、int height、int width、boolean bb){try {double ratio = 0.0; // scaling/*commonsmultipartfile cf =(commonsmultipartfile)file; diskfileitem fi =(diskfileitem)cf.getFileItem();ファイルf = fi.getStoreLocation();*///ファイルf = new File(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()){比率=(new integer(height))。 } else {ratio =(new Integer(width))。doublevalue() / bi.getWidth(); } affinetransformop op = new affinetransformop(affintransform .getscaleinstance(比率、比率)、null); item = 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、幅、高さ); if(width == item.getWidth(null))g.drawimage(itemp、0、(height -item.getheight(null)) / 2、item.getWidth(null)、item.getheigh(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(); item = image; } imageio.write((bufferedimage)item、 "jpg"、new file(result)); } catch(ioexception e){e.printstacktrace(); }} public static void main(string [] args){try {/* file file = new file( "e:// bole // doc // service interface document // boleサービスインターフェイス説明v1.0.docx"); system.out.println( "file =" + file);文字列json = submitfile(file); System.out.println( "json =" + json);*/} catch(Exception E){e.printstacktrace(); }}}画像トリミングツール
パッケージcom.shengya.service.utils; Import javax.imageio.imageio; Import javax.imageio.imagereadparam; Import javax.imageio.imagereader; Import javax.imageio.stream.imageinputstream; Import java.awt java.io.fileinputStream; Import java.io.ioException; Import java.util.iterator;/***は、2016/9/1に管理者によって作成されました。 */public class cutimgutils {// ===次のようなソースイメージパス名:c:/1.jpgプライベート文字列srcpath; // ===クリップ画像ストレージパス名。例:C:/2.jpgプライベートストリングサブパス。 public void setsrcpath(string srcpath){this.srcpath = srcpath; } public void setSubpath(String Subpath){this.subpath = subpath; } // ===スライスポイントx座標プライベートint x;プライベートインストY; // ===スリフトポイント幅private int width;プライベートINT高さ; 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 {//画像ファイルの読み取り= new fileinputStream(srcpath); /** * *現在登録されているすべてのImagreadersを含むIteratorを返します。これは、指定された形式をデコードできると主張します。パラメーター:formatname-非公式の形式名が含まれています。 * *( "jpeg"または "tiff")など。 */ iterator <mageReader> 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メソッドから返されます。 */ imageReadparam param = reader.getDefaulTreadParam(); /** * *画像収穫面積。長方形は、座標空間内の領域を指定します。これは、長方形オブジェクトの左上頂点の座標(x、y)、幅、高さで定義できます**。 */ rectangle rect = new Rectangle(x、y、幅、高さ); //緩衝液を提供して、ピクセルデータを解読するためのターゲットとして使用します。 param.setsourceregion(rect); /** *提供されたImagEReadParamを使用して、ImageIndexをインデックス作成して指定されたオブジェクトを読み取り、完全なBufferedImageとして * *を返します。 */ bufferedimage bi = reader.read(0、param); //新しいimage imageio.write(bi、 "jpg"、new file(subpath))を保存します。 file file = new file( "subpath");ファイルを返します。 }最後に{if(is!= null)is.close(); if(iis!= null)iis.close(); }} public file cut(string suffix)throws ioexception {fileinputStream is = null; ImageInputStream iis = null; try {//画像ファイルは= new fileinputStream(srcpath); // is = inputstream; /** *指定された形式をデコードできると主張する、現在登録されているすべてのImagEReadersを含むIteratorを返します。パラメーター:formatname-非公式の形式名が含まれています。 * *( "jpeg"または "tiff")など。 */ 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> *。 「フォワードのみ」としてマークします。 * * This setting means that images included in the input source will be read only in order, which may allow the reader * * to avoid cached those input portions containing data associated with previously read images. */ reader.setInput(iis, true); /** * * <p> * Class that describes how to decode streams* <p> * . Used to specify how to convert an image or set of images from a stream in the context of a Java Image I/O * * framework when input. Plugin for a specific image format* * * An instance of ImageReadParam will be returned from its ImageReader implementation's getDefaultReadParam method. */ 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(); }}}遇到的问题总结:
-裁剪图片发生偏移现象<br />解决办法:使用压缩后的图片等比例收集裁切坐标信息
-MultipartFile 和File之间相互转化
第一种方法:
MultipartFile file = xxx; CommonsMultipartFile cf= (CommonsMultipartFile)file; DiskFileItem fi = (DiskFileItem)cf.getFileItem(); File f = fi.getStoreLocation();
会在项目的根目录的临时文件夹下生成一个文件;
2番目の方法:
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/.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。