Dieser Artikel teilt einen vollständigen Fall des Hochladens von Bildern in Javaweb als Referenz. Der spezifische Inhalt ist wie folgt
Implementierungsideen
• Verwenden Sie das JCrop -Plugin, um die Koordinaten des Bildes auf Ihrem Telefon zu bestimmen
• Übergeben Sie die gesammelten Parameter an den Hintergrund. Verwenden Sie Java -Grafikobjekte, um Bilder zum Zuschneiden zu zeichnen
◦Background -Verarbeitungsfluss:
1. Komprimieren Sie die hochgeladenen Bilder proportional und laden Sie sie auf den Dateiserver hoch und speichern Sie die komprimierten Bilder in einem lokalen temporären Verzeichnis.
2. Echo das komprimierte Bild auf die Seite, verwenden Sie JCrop zum Anschneiden und klemmen Sie die Koordinaten auf dem Telefon (X, Y, Breite, Höhe).
■@paramx target Slice Startpunktkoordinate x
■@param y Das Ziel -Slice -Startpunktkoordinaten y
■@Parambreite Zielscheibenbreite ■@Paramhohenhöhe Zielschnitte Höhe
3.. Backstage -Verarbeitung von Zuschneiden und Hochladen
JSP -Seite
< %@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> < %@ page contentType = "text/html; charset = utf-8" Sprache = "java" %> <! docttml> <html> <heads "<mtml> <html> < content = "text/html; charSet = utf-8"/> <title> Laden Sie Benutzer avatar </title> <link href = "$ {pageContext.Request.ContextPath} /js/cutimg/CSS/Master.css" href = "$ {pageContext.request.contextpath} /js/cutimg/css/upload.css" rel = "styleSheet"/> <link href = "$ {pageContext.request.contextpath} /js/cutimg/cs.jquey.rollBar.S. /> <link href="${pageContext.request.contextPath}/js/cutImg/css/jquery.Jcrop.css" rel="stylesheet" /></head><body><div> <form id="uploadImgFrom" enctype="multipart/form-data" method="post"> <div> <div> <div> <div> <div> <div id = "pic2"> <div id = "uploadFile"> <div style = "margin-links: 75px;"> <a href = "javaScript:;" id="upText" style="color:red;">Upload avatar</a> </div> <p> Support jpg and png formats<br /> Picture less than 2M </p> </div> <!--Return to display pictures--> <img src="" name="photo" id="originalImg"/> </div> </div> <p id="up_reload" style="display: keine; "> <a href =" JavaScript:; " style = "color: rot"> repload </a> < /p> <Eingabe type = "Hidden" name = "picval" id = "picval" /> <input type = "Hidden" name = "origpicval" id = "origpicval" value = " /> <input type =" hidden "name =" temporigpic "id =" id = "id =" id = "id =" id = "" id = "id =" "id =" "id =" id = "" id = "id id = "fileId" size = "100" /> <Eingabe type = "hidden" name = "fileUrl" id = "fileUrl" size = "100" /> <Eingabe type = "Hidden" name = "imgHeight" id = "imgheeight" size = "100" /> <Eingabe type = "hidden". <img id = "preview_1" src = "$ {pageContext.request.contextPath} /images/4-3.jpg"/> </div> <p> 400 x 300 Pixel </p> <%-<div> <img id = "preview_2" src=${pageContext.request.contextPath}/images/4-3.jpg /> </div> <p> 80 x 80 pixels</p>--%> <p> Drag or zoom to generate a satisfactory avatar</p> </div> <%-- <div id="img_description"> <textarea </div>--%> <div> <font id = "upalert"> </font> </div> </div> </div> <input type name = "imgurl" id = "imgurl"/> <Eingabe type = "Hidden" name = "imgid" id = "imgid"/> <div> <div id = "SaveImage"> <a href = "javaScript:;" style="color: red">Save avatar</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.validat.min.js"> </script> <script type = "text/javaScript" src = "$ {pageContext.request.contextpath} /js/check.js.js"> </scrpty> </scripts textex = JavaSthock " src = "$ {pageContext.request.contextPath} /js/Check.js"> </script> <script src = "$ {pageContext.request.contextPath} /js/cutimg/js/jquery.7.Min.Min.js.js type" type 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-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/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"> fotos.jcorpwidth = 400; // Crop -Auswahlbox -Box -Photosa.jcorpheight = 300;/300; // // Crop -AuswahlboxhyothothTHTHTHTHTHTHOTHTHTHOTHTHTHTHTHTHTHTHODTHTHOTHTHTH -FOCSICTHTHTHODTHTHODTHTHALTH. ["200", "80"]; // Die Bildgröße "Breite" Array, definieren Sie die Breite verschiedener Bilder von groß zu klein nach der Anzahl der Bilder // Fotos fotos.upload_filetextId = "uptext"; // Komponent -Schaltfläche Text -ID -Fotos hochladen. "OriginalImg"; // Basisbild -ID fotos.upload_reloadid = "up_reload"; // REUpload -Komponent -ID -Fotos. fotos. "origpicval"; // Die Originalbildinhalt -ID Wenn andere Seiten fotos eingeben "Präfix" + Nummer (ab 1), Beispiel: id = "photos_preview1" ... fotos.parentFileMgid = "imgurl"; // übergeordnete Bildkontroll -ID -Fotos. "H"; // H fotos.uptext_format = "Entschuldigung, nur JPG-, PNG- und BMP -Formate werden zum Zeitpunkt unterstützt." "/Enterprise/fileCheck"; // Adressfotos.url_Upload = "/Enterprise/UploadPhoto? Up = Original"; // Image Lade -Basis -Bild fotos.url_reload = ""; // adresse fotos reload fotos reload fotos neuHintergrund Java -Code
Bild -Upload -Tool
Paket com.shengya.service.utils; import com.shengya.service.imgcontants; import org.apache.commons.FileUpload.disk.diskFileItem; org.springframework.web.multipart.commons.CommonsMultipartFile; Import Sun.misc.base64Coder; Import Javax.crypto.Mac; Import Javax.crypto.Secretkey; Import Javax.imto.specretkeySpec; javax.imageo.imagereadparam; import Java.awt. java.net.urlencoder; import Java.util.ArrayList;/** * @Author Darcy * Erstellt von Administrator am 2016/6/17. */öffentliche Klasse Uploadutils {// öffentliche endgültige statische 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?"; öffentliche endgültige statische Zeichenfolge url = imgContants.img_Upload + "/Datei/UploadImage?"; public Final static String fileurl = imgContants.img_Upload + "/Datei/Uploadfile?"; öffentliche endgültige statische String vediourl = imgContants.file_Upload + "/Datei/Uploadfile?"; public Final Static String cropurl = imgcontants.img_Upload + "/Datei/Cropimage?"; privates statisches Byte [] readasBytearr (InputStream ist) {bytearrayoutputStream baos = new bytearrayoutputStream (); try {byte [] bytes = new Byte [1024]; int länge = 0; while ((länge = is.read (bytes))! = -1) {baos.write (bytes, 0, länge); } return baos.tobytearray (); } catch (Ausnahme e) {e.printstacktrace (); } endlich {try {baos.close (); } catch (ioException e) {e.printstacktrace (); }} return null; } / ** * Bild hochladen * * @param Datei * / public static String surfenImage (Dateidatei) löscht die nicht supportedenCodingException {String FileName = urlencoder.encode (Datei.getName (), "utf-8") aus; Long FileSize = Datei.length (); boolean isResuffix = true; int Höhe = 0; int width = 500; String mark = "t"; String modus = "w"; String url = sign (url) + "& Channelno = muying_android" + "& fileName =" + Dateiname + "& fideSize =" + filesize + "& isResuffix =" + isResuffix + "& height =" + Höhe + "& width =" + width + "& mark =" + "& modus =" + " +" (" +" + "Modus". System.out.println ("url:" + url); HttpurlConnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; try {bin = new buferedInputStream (new FileInputStream (Datei)); conn = (httpurlConnection) neue URL (URL) .OpenConnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); conn.setDooutput (true); // conn.setFixedLengthStreamingMode (Datei.length ()); Conn.SetRequestProperty ("Content-Typ", "Anwendung/x-www-form-urlencoded"); Conn.SetRequestProperty ("Inhaltslänge", File.length () + ""); // Conn.SetRequestProperty ("Bereich", "Bytes ="+""); // Setzen Sie die Zeichencodierung von httpurlConnection conn.setRequestProperty ("Accept-charset", "UTF-8"); outstream = conn.getOutputStream (); byte [] buf = neues byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! } outstream.flush (); int responseCode = conn.getresponsecode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; } else {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; }} catch (Ausnahme e) {e.printstacktrace (); } endlich {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printstacktrace (); }} return null; } / ** * Bild hochladen * * @param-Datei * / public static String subayWebImage (MultiPartFile-Datei) löscht unupportEneTeCodingException {String FileName = urlencoder.encode (Datei.GetoriginalFileName (), "utf-8"); Long FileSize = Datei.getSize (); boolean isResuffix = true; int Höhe = 0; int width = 500; String mark = "t"; String modus = "w"; String url = sign (url) + "& Channelno = muying_android" + "& fileName =" + Dateiname + "& fideSize =" + filesize + "& isResuffix =" + isResuffix + "& height =" + Höhe + "& width =" + width + "& mark =" + "& modus =" + " +" (" +" + "Modus". System.out.println ("url:" + url); HttpurlConnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; try {bin = new buferedInputStream (file.getInputStream ()); conn = (httpurlConnection) neue URL (URL) .OpenConnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); conn.setDooutput (true); // conn.setFixedLengthStreamingMode (Datei.length ()); Conn.SetRequestProperty ("Content-Typ", "Anwendung/x-www-form-urlencoded"); Conn.SetRequestProperty ("Inhaltslänge", File.getSize () + ""); // Conn.SetRequestProperty ("Bereich", "Bytes ="+""); // Setzen Sie die Zeichencodierung von httpurlConnection conn.setRequestProperty ("Accept-charset", "UTF-8"); outstream = conn.getOutputStream (); byte [] buf = neues byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! } outstream.flush (); int responseCode = conn.getresponsecode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; } else {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; }} catch (Ausnahme e) {e.printstacktrace (); } endlich {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printstacktrace (); }} return null; } / ** * Video hochladen * * @param Datei * / public static String subestRadio (MultiPartFile -Datei) löst eine Ausnahme aus {String url = signradio (radiourl); System.out.println ("url:" + url); HttpurlConnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; try {bin = new buferedInputStream (file.getInputStream ()); conn = (httpurlConnection) neue URL (URL) .OpenConnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); conn.setDooutput (true); Conn.SetRequestProperty ("Content-Typ", "Anwendung/x-www-form-urlencoded"); Conn.SetRequestProperty ("Inhaltslänge", File.getSize () + ""); Conn.SetRequestProperty ("Accord-Charset", "UTF-8"); outstream = conn.getOutputStream (); byte [] buf = neues byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! } outstream.flush (); int responseCode = conn.getresponsecode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; } else {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; }} catch (Ausnahme e) {e.printstacktrace (); } endlich {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printstacktrace (); }} return null; } /** * REPLAD REFOME SNAPSHOT * * @PARAM Dateiname * @param content * @return * @throws UnsupportedenCodingException * /public static String Subschritt (String-Dateiname, String-Inhalt) löscht UnsupportedenCodingException {// content = urlencoder.encodode (content, "utf-8"); fileName = urlencoder.encode (Dateiname, "utf-8"); byte [] contentBytes = content.getBytes (); Long FileSize = contentBytes.length; boolean isResuffix = true; int Höhe = 0; int width = 500; String mark = "t"; String modus = "w"; String url = Sign (FileURL) + "& ChannelNO = muying_android" + "& fileName =" + Dateiname + "& fidesize =" + filesize + "& isResuffix =" + isResuffix + "& height =" + Höhe + "& width =" + width + "& mark =" + "& modmod =" + " +" + ". 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 (Datei.length ()); Conn.SetRequestProperty ("Content-Typ", "Anwendung/x-www-form-urlencoded"); Conn.SetRequestProperty ("Inhaltslänge", content.length () + ""); // Conn.SetRequestProperty ("Bereich", "Bytes ="+""); // Setzen Sie die Zeichencodierung von 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 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; } else {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; }} catch (Ausnahme e) {e.printstacktrace (); } endlich {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printstacktrace (); }} return null; } / *** Anhang hochladen** @return json string* @throws UnsupportedenCodingException* / public static String Subschritt (MultiPartFile-Datei) löscht unportiereneCodingException {String FileName = urlencoder.encode (Datei. Long FileSize = Datei.getSize (); boolean isResuffix = true; int Höhe = 0; int width = 500; String mark = "t"; String modus = "w"; String url = Sign (FileURL) + "& ChannelNO = muying_android" + "& fileName =" + Dateiname + "& fidesize =" + filesize + "& isResuffix =" + isResuffix + "& height =" + Höhe + "& width =" + width + "& mark =" + "& modmod =" + " +" + ". System.out.println ("url:" + url); HttpurlConnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; try {bin = new buferedInputStream (file.getInputStream ()); conn = (httpurlConnection) neue URL (URL) .OpenConnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); conn.setDooutput (true); // conn.setFixedLengthStreamingMode (Datei.length ()); Conn.SetRequestProperty ("Content-Typ", "Anwendung/x-www-form-urlencoded"); Conn.SetRequestProperty ("Inhaltslänge", File.getSize () + ""); // Conn.SetRequestProperty ("Bereich", "Bytes ="+""); // Setzen Sie die Zeichencodierung von httpurlConnection conn.setRequestProperty ("Accept-charset", "UTF-8"); outstream = conn.getOutputStream (); byte [] buf = neues byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! } int responseCode = conn.getresponsecode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; } else {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; }} catch (Ausnahme e) {e.printstacktrace (); } endlich {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printstacktrace (); }} return null; } private statische String -Sign (String BaseUrl) löst nicht unterstütztEcodingException {long Currency = System.currentTimemillis () aus; langer Zeitstempel = Währung / 1000; String data = "actionName = uploadImage" + "& secryKey = 4b19f08dbf0Adb82ce9cc7c207ec1dc9" + "& timestamp =" + timestamp; String Signature = HMAC_SHA1 ("4B19F08DBF0ADB82CE9CC7C207EC1DC9", urlencoder.encode (Daten, "UTF-8"); Signatur = Signatur.Replace ("%3D", "%3D"); Signatur = Signatur.Replace ("%3a", "%3a"); Signatur = Signatur.Replace ("%2f", "%2f"); return baseUrl + data + "& signature =" + Signatur; } private statische String Signradio (String url) löst Ausnahme aus {Long CurrencyBtime = System.currentTimemillis (); String Data = "SecretKey = F1B79C865C424BE46183A2F0A49A0F15" + "& Timestamp =" + Währung; 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"); URL + Daten zurückgeben + "& signature =" + Signatur; } private statische String hmac_sha1 (String -Schlüssel, String -Daten) {String resting = ""; try {datas = datas.replace ("%3a", "%3a"); datas = datas.replace ("%2f", "%2f"); datas = datas.replace ("%3D", "%3D"); byte [] data = key.getBytes ("utf-8"); // Erstellen Sie einen Schlüssel, der auf dem angegebenen Byte -Array basiert, und der zweite Parameter gibt den Namen eines Schlüsselalgorithmus SecretKey SecretKey = New SecretKeyspec (Daten, "hmacsha1") an; // ein Mac -Objekt mit dem angegebenen Mac -Algorithmus Mac Mac = mac.getInstance ("hmacsha1") generieren; // Initialisieren Sie das Mac -Objekt mit dem angegebenen Schlüssel Mac.init (SecretKey); byte [] text = datas.getBytes ("utf-8"); // MAC Operation Byte [] text1 = mac.dofinal (text) komplett; resting = new Base64EnenCoder (). EncodeBuffer (text1); resting = urlencoder.encode (resting, "utf-8"); resting = resting.replace ("%0a", ""); resting = resting.replace ("%0d", ""); } catch (Ausnahme e) {e.printstacktrace (); } return resting; }/** * hochgeladenes Bild hochladen. String [] cropwidths = new String [] {"50"}; // Crop -Breite // 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> listCropheTs = new ArrayList <string> (); listCropheighths.add ("300"); int cropx = integer.parseInt (x); // crop x coordinate int cropy = integer.parseInt (y); // crop y coordinates // String [] cropfixs = new String [] {"l"}; // crop Image Marke Set arraylist <string <string> listCropfixs = new Arraylist <string> () (); listCropfixs.add ("l"); String Quellensuffix = "JPG"; // Basiskarten -Suffix String SourceFix = ""; // Basiskarten -Logo/* boolean isResuffix = true; int Höhe = 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 buferedInputStream (file.getInputStream ()); conn = (httpurlConnection) neue URL (URL) .OpenConnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); conn.setDooutput (true); // conn.setFixedLengthStreamingMode (Datei.length ()); Conn.SetRequestProperty ("Content-Typ", "Anwendung/x-www-form-urlencoded"); Conn.SetRequestProperty ("Inhaltslänge", File.getSize () + ""); // Conn.SetRequestProperty ("Bereich", "Bytes ="+""); // Setzen Sie die Zeichencodierung von httpurlConnection conn.setRequestProperty ("Accept-charset", "UTF-8"); outstream = conn.getOutputStream (); byte [] buf = neues byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! } int responseCode = conn.getresponsecode (); if (responseCode == 200) {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; } else {inputStream instream = conn.getInputStream (); byte [] data1 = lesasBytearr (Instrenkung); String json = new String (Data1); instream.close (); Rückkehr JSON; }} catch (Ausnahme e) {e.printstacktrace (); } endlich {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printstacktrace (); }} return null; }/** Das Bild muss nach dem Hochladen und Zuschneiden lokal gespeichert werden. String order = system.getProperty ("java.io.tmpdir"); Datei tempdir = neue Datei (Ordner); // Wenn der Ordner nicht existiert, erstellen Sie if (! Tempdir .exists () &&! Tempdir .isdir ()) {// system.out.println ("// nicht existiert"); tempdir .mkdir (); } // komprimierte temporäre Dateistring srcpath = Ordner+"scalETemp.jpg"; // Erhalten Sie das Suffix der Datei/*Datei uploadFile = neue Datei (SRCPath); InputStream inputStream = file.getInputStream (); FileInputStream fs = (FileInputStream) inputStream; String srcimg = urlencoder.encode (Datei.getOriginalFileName (), "utf-8"); String -Suffix = srcimg.substring (srcimg.lastIndexof (".")+1);*// Ernte das Bild Cutimgutils o = neue Cutimgutils (x, y, w, h); O.SetsrcPath (srcPath); O.SetsubPath (Ordner+"upTemp.jpg"); Datei tempfile = o.cut ("jpg"); String S = Subjekt (tempfile); Rückkehr s; }/** * Erhalten Sie die Breite des hochgeladenen Bildes * Zxiao 2016/09/09 * @param -Datei * @return */public static int getImgWidth (MultiPartFile -Datei) löscht IOException {InputStream is = null; Bufferedimage src = null; int ret = -1; try {is = file.getInputStream (); src = javax.imageo.imageio.read (IS); ret = src.getwidth (null); // Die Quellbildbreite is.CLOSE () abrufen; } catch (Ausnahme e) {e.printstacktrace (); } return ret; }/** * das hochgeladene Bild hoch erhalten Bufferedimage src = null; int ret = -1; try {is = file.getInputStream (); src = javax.imageo.imageio.read (IS); ret = src.getheight (null); // Die Quellbildhöhe is.CLOSE () abrufen; } catch (Ausnahme e) {e.printstacktrace (); } return ret; } /*** skalieren Bild (Skalierung nach Höhe und Breite)* @Param -Datei -Dateiobjekt* @param Ergebnisskala Bildadresse* @param Höhenskala Höhe* @Param Breitskala Breite* @param BB ist erforderlich, wenn die Skalierung falsch ist: TRUE: TRUE IS A FISS; Falsch ist nicht ausfüllt; */ public static void Skala (MultiPartFile -Datei, String -Ergebnis, inthöhe, int breit, boolean bb) {try {Double -Verhältnis = 0,0; // scaling/*commonsMultiPartFile cf = (commonsMultipartFile) Datei; DiskFileItem fi = (diskFileItem) vgl. GETFILEITEM (); Datei f = fi.getStorelocation ();*/// Datei f = Neue Datei (srcimageFile); InputStream inputStream = file.getInputStream (); Bufferedimage bi = imageio.read (InputStream); Bildelement = bi.getScaledInstance (Breite, Höhe, bi.scale_smooth); // Berechnen Sie die Skala if ((bi.getheight ()> Höhe) || (bi.getwidth ()> width) {if (bi.getheight ()> bi.getwidth ()) {rettio = (neu Integer (Höhe)). } else {Ratio = (New Integer (Breite)). DoubleValue () / bi.getWidth (); } Affinetransformop op = new Affinetransformop (Affinetransform .GetScaleinstance (Verhältnis, Verhältnis), NULL); item = op.filter (bi, null); } if (bb) {// füllen buffenedImage image = new bufferedImage (width, Höhe, bufferedimage.type_int_rgb); Graphics2d g = Bild.CreateGraphics (); G.SetColor (color.white); G.FillRect (0, 0, Breite, Höhe); if (width == item.getWidth (null)) g.drawimage (itemp, 0, (Höhe - item.getheight (null)) / 2, item.getwidth (null), item.getheight (null), color.white, null); sonst g.drawimage (itemp, (width - item.getwidth (null)) / 2, 0, item.getWidth (null), item.getheight (null), color.white, null); g.disponse (); Element = Bild; } Imageio.write ((bufferedImage) item, "JPG", neue Datei (Ergebnis)); } catch (ioException e) {e.printstacktrace (); }} public static void main (string [] args) {try {/* Dateidatei = new File ("e: // bole // doc // Service Interface Dokument // Bole Service Interface Beschreibung v1.0.docx"); System.out.println ("file =" + Datei); String json = subledFile (Datei); System.out.println ("json =" + json);*/} catch (Ausnahme e) {e.printstacktrace (); }}} Bildfruchtwerkzeuge
Paket com.shengya.service.utils; import Javax.imageo.imageo; Import Javax.imageo.imagereadParam; Import Javax.imageo.imagereader; Import Javax.imageio.stream.imageInputStream; Import Java.awt. Java.io.FileInputStream; Import Java.io.ioException; Import Java.util.iterator;/*** Erstellt vom Administrator unter 2016/9/1. */öffentliche Klasse Cutimgutils {// === Der Quellbild -Pfadname wie: c: /1.jpg private String srcPath; // === Der Name des Clip -Bildspeichers. Zum Beispiel: C: /2.jpg privater String -Subpath; public void setsrcPath (String srcPath) {this.srcpath = srcPath; } public void setSubPath (String subpath) {this.subpath = subpath; } // === Slice Point x Koordinate private int x; privat int y; // === Slift Point Breite private int Breite; private int Höhe; public Cutimgutils () {} public Cutimgutils (int x, int y, int width, int Höhe) {if (x <0) {x = 0; } else {this.x = x; } if (y <0) {y = 0; } else {this.y = y; } this.width = width; this.height = Höhe; } /** * * Ernte das Bild und speichere das neue Bild nach dem Zuschneiden. */ public File cut () löscht ioException {FileInputStream is = null; ImageInputStream iis = null; Versuchen Sie {// Bilddateien lesen ist = new FileInputStream (SRCPath); /** * * Gibt Iterator zurück, die alle aktuell registrierten Imagleräer enthalten, die behaupten, das angegebene Format zu dekodieren. Parameter: Formatname - enthält den informellen Formatnamen. * * (wie "jpeg" oder "tiff") usw. */ iterator <FileReader> it = imageIO .getImagereAlsByFormatName ("JPG"); ImageReader reader = it.Next (); // den Bildstrom abrufen iis = imageio.createimageInputStream (IS); /** * * <p> * iis: Lesen Sie die Quelle. Richtig: Nur nach vorne suchen * </p> *. Markieren Sie es als "nur nach vorne suchen". * * Diese Einstellung bedeutet, dass Bilder, die in der Eingangsquelle enthalten sind, nur in der Reihenfolge gelesen werden, wodurch der Leser * * vermieden werden kann, dass diese Eingangspartionen, die Daten enthalten, die mit zuvor gelesenen Bildern zugeordnet sind. */ reader.setInput (iis, true); /** * * <p> * Klasse, die beschreibt, wie Streams * <p> * dekodieren. Wird verwendet, um anzugeben, wie ein Bild oder eine Reihe von Bildern aus einem Stream im Kontext eines Java -Bild -E/O * * -Regeltes bei der Eingabe konvertiert werden. Plugin für ein bestimmtes Bildformat * * * Eine Instanz von ImagereadParam wird von der GetDefaulTreadParam -Methode der ImaglereAder -Implementierung zurückgegeben. */ ImageReadParam param = reader.getDefaultreadParam (); /** * * Bildernte. Rechteck legt einen Bereich im Koordinatenraum an, der durch die Koordinate (x, y), die Breite und Höhe des oberen linken Scheitelpunkts des Rechteckobjekts ** definiert werden kann. */ Rechteck rechteck = neues rechteck (x, y, breite, Höhe); // Geben Sie ein gepuffertes Diplomage zur Verfügung, um es als Ziel für die Entschlüsselung von Pixeldaten zu verwenden. Param.SetSourCeregion (rect); /** * Verwenden Sie das bereitgestellte ImagereadParam, um das durch Indexierung von ImageIndex angegebene Objekt zu lesen und * * als vollständiger gepufferter Abschluss zurückzugeben. */ Bufferedimage bi = reader.read (0, param); // neue Image Imageio.write (bi, "jpg", neue Datei (Subpath)) speichern; Datei Datei = new Datei ("subpath"); Rückgabedatei; } endlich {if (is! = null) ist.CLOSE (); if (iis! = null) iis.close (); }} public File Cut (String -Suffix) löscht IOException {FileInputStream is = null; ImageInputStream iis = null; Versuchen Sie {// Lesen Sie die Bilddatei IS = new FileInputStream (srcPath); // is = inputStream; /** * Gibt den Iterator zurück, der alle aktuell registrierten Imagleräer enthält * *, die behaupten, das angegebene Format zu dekodieren. Parameter: Formatname - enthält den informellen Formatnamen. * * (wie "jpeg" oder "tiff") usw. * Iterator <FileReader> iT = imageIO.getImagereadersByFormatName ("JPG"); */ String Suffixname = null; if (suffix.equals ("gif")) {suffixname = "gif"; } else if (suffix.equals ("png")) {SuffixName = "png"; } else {suffixname = "jpg"; } Iterator <FileReader> iT = imageIO .GetImagereArerByFormatName (SuffixName); ImageReader reader = it.Next (); // den Bildstrom abrufen iis = imageio.createimageInputStream (IS); /** * * <p> * iis: Lesen Sie die Quelle. Richtig: Nur nach vorne suchen * </p> *. Markieren Sie es als "nur nach vorne suchen". * * Diese Einstellung bedeutet, dass Bilder, die in der Eingangsquelle enthalten sind, nur in der Reihenfolge gelesen werden, wodurch der Leser * * vermieden werden kann, dass diese Eingangspartionen, die Daten enthalten, die mit zuvor gelesenen Bildern zugeordnet sind. */ reader.setInput (iis, true); /** * * <p> * Klasse, die beschreibt, wie Streams * <p> * dekodieren. 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(); /** * * Image crop area. Rectangle specifies an area in the coordinate space, which can be defined by the coordinate (x, y), width, and height of the upper left vertex of the Rectangle object **. */ Rectangle rect = new Rectangle(x, y, width, height); // Provide a BufferedImage to use it as the target for decoding pixel data. param.setSourceRegion(rect); /** * Use the provided ImageReadParam to read the object specified by indexing imageIndex and return * * as a complete BufferedImage. */ BufferedImage bi = reader.read(0, param); // Save new image 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之间相互转化
Die erste Methode:
MultipartFile file = xxx; CommonsMultipartFile cf= (CommonsMultipartFile)file; DiskFileItem fi = (DiskFileItem)cf.getFileItem(); File f = fi.getStoreLocation();
会在项目的根目录的临时文件夹下生成一个文件;
Die zweite Methode:
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); // 得到源图宽
Referenzen:
jcop api:http://code.ciaoca.com/jquery/jcrop/.
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.