Cet article partage un cas complet de téléchargement d'images dans Javaweb pour référence. Le contenu spécifique est le suivant
Idées de mise en œuvre
• Utilisez le plugin JCROP pour couper les coordonnées de l'image sur votre téléphone
• Passez les paramètres collectés à l'arrière-plan, utilisez des objets graphiques Java pour dessiner des images pour le recadrage
◦ Flux de traitement du sol:
1. Compressez les images téléchargées en proportion et téléchargez-les sur le serveur de fichiers, et enregistrez les images compressées dans un répertoire temporaire local.
2. Faites écho à l'image compressée sur la page, utilisez JCROP pour le recadrage et coupez les coordonnées sur le téléphone (x, y, largeur, hauteur)
■ @ Paramx Target Slice Start Point Point Point X
■ @ param y La coordonnée du point de départ de la tranche cible Y
■ @ Largeur de paramètre Largeur de tranche cible ■ @ PARAM HEAUT HAUTE
3. Traitement des coulisses des coulisses et téléchargement
page jsp
<% @ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> <% @ page ContentType = "Text / html; charset = utf-8" Language = "Java"%> <! doctype html> <html> <read> <méta HTTP-EQUIS Content = "Text / Html; charSet = UTF-8" /> <Title> Upload l'utilisateur Avatar </ Title> <link href = "$ {pagecontex href = "$ {pagecontext.request.contextpath} /js/cutimg/css/upload.css" rel = "Stylesheet" /> <link href = "$ {pageContex href = "$ {pagecontext.request.contextpath} /js/cutimg/css/jquery.jcrop.css" rel = "Stylesheet" /> </ head> <body> <div> <form id = "uploadimgfrom" enctype = "multipart / form-data" méthode = "post"> <v> id = "pic2"> <div id = "uploadfile"> <div style = "margin-left: 75px;"> <a href = "javascript:;" id = "uptext" style = "couleur: rouge;"> télécharger avatar </a> </div> <p> Prise en charge des formats jpg et png <br /> images inférieures à 2m </p> </ div> <! - Retour pour afficher des images Aucun; "> <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 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" /> <entrée type = "HIDDEN" name = "imgwidth" id = "imgwidth" size = "100" 100 "/> </ div> <div> <imgwidth" size = "100" 100 "/> id = "aperview_1" src = "$ {pagecontext.request.contextpath} /images/4-3.jpg" /> </ div> <p> 400 x 300 pixels </p> <% - <v> <img id = "Preview_2" src = $ {pagecontex </div> <p> 80 x 80 pixels </p> - %> <p> Faites glisser ou zoom pour générer un avatar satisfaisant </p> </div> <% - <div> <font id = "upaLert"> </font> </v> </v> <font <font id = "upaLert"> </font> </v> </v> </vont> <font div> id = "x" 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" /> <entrée = "Hidden" nom = "imgid" id = "imgid" /> <entrée = " id = "SaveImage"> <a href = "javascript:;" Style = "Color: Red"> Enregistrer Avatar </a> </div> </ div> </ form> </div> </ body> <script type = "Text / Javascrip src = "$ {pagecontext.request.contextpath} /js/jquery.validate.min.js"> </ script> <script type = "text / javascript" src = "$ {pagecontex src = "$ {pagecontext.request.contextpath} /js/check.js"> </ script> <script src = "$ {pagecontex src = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery.form.js" type = "text / javascrip type = "text / javascript"> </ script> <script src = "$ {pagecontex src = "$ {pagecontext.request.contextpath} /js/cutimg/js/jquery.jcrop.js" type = "text / javascript"> </ script> <script src = "$ {pagecontext.request.contextpath} /js/cutimg/js/jQuery.rollbar. 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 / javascrip "80"]; // le tableau de la taille de la taille de la taille de l'image, définissez la largeur de différentes images de grande à petite selon le nombre de photos // photos.Heights = ["200", "80"]; // la taille de l'image "High" tableau, définissez la hauteur de différentes images de grande enver "uptext"; // Téléchargez le bouton du composant ID de texte Photos.Upload_Alertid = "upaLert"; // "up_reload"; // id de composant reupload Photos.upload_picValueId = "picval"; // Téléchargez le contenu de l'image inférieur Photos.upload_picfileId = "FileId"; /// téléchargez l'identification des photos.upload_picfileUrl = "FileUrl"; // up up url Photos.upload_picgghegHeight = "IMGHEORD" Image de base téléchargée High Photos.upload_picimgWidth = "imgwidth"; // L'image de base téléchargée large Photos.Upload_TemporiginValueId = "temporigpic"; // L'ID de contenu d'image d'origine lorsque cette page est re-téléchargée Photos.upload_originValueId = "OrigpicVal"; // Le contenu d'image original lorsque les autres pages entrent en photos. "pic2"; // ID de barre de scroll personnalisé Photos.Upload_saveid = "SaveImage"; // L'image d'enregistrement du bouton ID Photos.Upload_previewprefix = "Aperçu _"; // Le nom du préfixe d'ID de plusieurs petites images de différentes tailles, le format d'identification de plusieurs petites images " "imgurl"; // id de contrôle d'image parent photos photos.parentFileValueId = "imgid"; // parent de contrôle d'adresse de l'image id Photos.Xid = "x"; // x photos.yid = "y"; // y photos.wid = "w"; Être "; // Texte de vérification du format d'image / * Photos.Uptext_size =" Désolé, la taille de l'image ne peut pas dépasser 2m "; * // Taille de la taille de l'image Text / * Photos.Uptext_error =" Erreur de téléchargement d'image "; // Téléchargez le texte d'erreur * / Photos.url_check =" Enterprise / Filescheck "; // Address Photos.Url_upload =" / enterprise / uploadpho? Image Chargement de base Image Photos.url_reload = ""; // Reload Address Photos.url_save = "/ Enterprise / SaveImg? Up = Save"; // L'adresse de l'image est enregistrée </ script> </ html>Code java arrière
Outil de téléchargement d'image
package com.shengya.service.utils; import com.shengya.service.imgcontines; import org.apache.commons.fileupload.disk.diskfileItem; import org.springframework.web.multiplart.multiplartfile; importation; importation; org.springframework.web.multiparpart.commons.commonsMultupartfile; Import Sun.Misc.base64encoder; import javax.crypto.mac; importer 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.io. *; import java.net.httpurlconnection; import java.net.url; java.net.urlencoder; import java.util.arraylist; / ** * @author darcy * créé par l'administrateur sur 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?"; Url de chaîne statique finale publique = 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 Cromberl = imgContants.img_upload + "/ file / CropImage?"; octet statique privé [] readasbytearr (inputStream is) {bytearrayoutputStream baos = new bytearrayoutputStream (); try {byte [] bytes = new byte [1024]; int length = 0; while ((length = is.read (octets))! = -1) {baos.write (octets, 0, longueur); } return baos.toByteArray (); } catch (exception e) {e.printStackTrace (); } enfin {try {baos.close (); } catch (ioException e) {e.printStackTrace (); }} return null; } / ** * Téléchargez l'image * * @param file * / public static String soumeImage (file file) lève unportdencodingException {string filename = urlencoder.encode (file.getName (), "utf-8"); long fileSize = file.length (); booléen iSResuffix = true; int hauteur = 0; Int largeur = 500; String Mark = "T"; Mode de chaîne = "W"; String url = signe (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 (fichier)); Conn = (httpurlConnection) Nouvelle URL (URL) .OpenConnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); Conn.SetDoOutput (true); // Conn.SetFixedLength StreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application / X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("Content-Length", File.Length () + ""); // conn.setRequestProperty ("range", "bytes =" + ""); // Définissez le codage des caractères de HttpurlConnection Conn.SetRequestProperty ("Accept-Charset", "UTF-8"); outstream = conn.getOutputStream (); octet [] buf = nouveau octet [1024]; int len = 0; int lentcount = 0; while ((Len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok Lencount = LenCount + len; } outstream.flush (); int qui resensowcode = conn.getResponSECODE (); if (répondeCode == 200) {inputStream insiteam = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; } else {inputStream instream = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; }} catch (exception e) {e.printStackTrace (); } enfin {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printStackTrace (); }} return null; } / ** * Upload Image * * @param File * / public static String soumedWeBimage (Fichier multipartFile) lève unportEncodingException {String filename = urlencoder.encode (file.getoriginalFileName (), "utf-8"); long fileSize = file.getSize (); booléen iSResuffix = true; int hauteur = 0; Int largeur = 500; String Mark = "T"; Mode de chaîne = "W"; String url = signe (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) Nouvelle URL (URL) .OpenConnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); Conn.SetDoOutput (true); // Conn.SetFixedLength StreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application / X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("Content-Length", file.getSize () + ""); // conn.setRequestProperty ("range", "bytes =" + ""); // Définissez le codage des caractères de HttpurlConnection Conn.SetRequestProperty ("Accept-Charset", "UTF-8"); outstream = conn.getOutputStream (); octet [] buf = nouveau octet [1024]; int len = 0; int lentcount = 0; while ((Len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok Lencount = LenCount + len; } outstream.flush (); int qui resensowcode = conn.getResponSECODE (); if (répondeCode == 200) {inputStream insiteam = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; } else {inputStream instream = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; }} catch (exception e) {e.printStackTrace (); } enfin {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printStackTrace (); }} return null; } / ** * Téléchargez la vidéo * * @param fichier * / public static String soumedRadio (fichier multipartfile) lève une exception {String url = signadio (radiourl); System.out.println ("URL:" + URL); Httpurlconnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; try {bin = new BufferedInputStream (file.getInputStream ()); Conn = (httpurlConnection) Nouvelle 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 (); octet [] buf = nouveau octet [1024]; int len = 0; int lentcount = 0; while ((Len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok Lencount = LenCount + len; } outstream.flush (); int qui resensowcode = conn.getResponSECODE (); if (répondeCode == 200) {inputStream insiteam = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; } else {inputStream instream = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; }} catch (exception e) {e.printStackTrace (); } enfin {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printStackTrace (); }} return null; } / ** * Upload Resume snapshot * * @param filename * @param contenu * @return * @throws UnportEdenCcodingException * / public static string soumedfile (string filename, String Content) lève unportedEncodingException {// contenu = urlencoder.encode (contenu, "utf-8"); filename = urlencoder.encode (filename, "utf-8"); Byte [] contentBytes = content.getBytes (); Long FileSize = ContentBytes.Length; booléen iSResuffix = true; int hauteur = 0; Int largeur = 500; String mark = "t"; Mode de chaîne = "W"; String url = signe (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; essayez {conn = (httpurlconnection) new URL (url) .openconnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); Conn.SetDoOutput (true); // Conn.SetFixedLength StreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application / X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("Content-Length", Content.Length () + ""); // conn.setRequestProperty ("range", "bytes =" + ""); // Définissez le codage des caractères de HttpurlConnection Conn.SetRequestProperty ("Accept-Charset", "UTF-8"); outstream = conn.getOutputStream (); outstream.write (contentBytes, 0, contentBytes.length); // ok outstream.flush (); int qui resensowcode = conn.getResponSECODE (); if (répondeCode == 200) {inputStream insiteam = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; } else {inputStream instream = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; }} catch (exception e) {e.printStackTrace (); } enfin {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printStackTrace (); }} return null; } / ** * Téléchargez la pièce jointe * * @return JSON String * @Throws UnsupporTeDenCcodingException * / public static String SoumisFile (Fichier multipartFile) lance unportEnCcodException {String FileName = Urlencoder.encode (file.getoriginalFileName (), "utf-8"); long fileSize = file.getSize (); booléen iSResuffix = true; int hauteur = 0; Int largeur = 500; String mark = "t"; Mode de chaîne = "W"; String url = signe (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) Nouvelle URL (URL) .OpenConnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); Conn.SetDoOutput (true); // Conn.SetFixedLength StreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application / X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("Content-Length", file.getSize () + ""); // conn.setRequestProperty ("range", "bytes =" + ""); // Définissez le codage des caractères de HttpurlConnection Conn.SetRequestProperty ("Accept-Charset", "UTF-8"); outstream = conn.getOutputStream (); octet [] buf = nouveau octet [1024]; int len = 0; int lentcount = 0; while ((Len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok Lencount = LenCount + len; } int qui réponde = conn.getResponSECODE (); if (répondeCode == 200) {inputStream insiteam = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; } else {inputStream instream = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; }} catch (exception e) {e.printStackTrace (); } enfin {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printStackTrace (); }} return null; } Sign de chaîne statique privée (String BasiseUrl) lève unportdencodingException {long devise = System.CurrentTimeMillis (); Timestamp long = devise / 1000; String data = "ActionName = uploadImage" + "& SecretKey = 4b19f08dbf0adb82ce9cc7c207ec1dc9" + "& timestamp =" + timestamp; String Signature = HMAC_SHA1 ("4B19F08DBF0ADB82CE9CC7C207EC1DC9", urlencoder.encode (données, "UTF-8")); signature = signature.replace ("% 3D", "% 3D"); signature = signature.replace ("% 3a", "% 3a"); signature = signature.replace ("% 2f", "% 2f"); return BUSTISURL + DATA + "& Signature =" + Signature; } chaîne statique privée signadio (URL de chaîne) lève une exception {Long CurrencyBttime = System.currentTimeMillis (); String data = "SecretKey = F1B79C865C424BE46183A2F0A49A0F15" + "& timestamp =" + devise; 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 de retour + données + "& signature =" + signature; } chaîne statique privée hmac_sha1 (key string, string datas) {String restring = ""; essayez {datas = datas.replace ("% 3a", "% 3a"); datas = dataS.replace ("% 2f", "% 2f"); datas = dataS.replace ("% 3D", "% 3D"); Byte [] data = key.getBytes ("utf-8"); // Construisez une clé basée sur le tableau d'octets donné, et le deuxième paramètre spécifie le nom d'un algorithme clé SecretKey SecretKey = new SecretKeyspec (DATA, "HMACSHA1"); // Générez un objet Mac avec l'algorithme Mac spécifié mac mac = mac.getInstance ("hmacsha1"); // Initialisez l'objet Mac avec la clé donnée Mac.Init (SecretKey); Byte [] text = dataS.getBytes ("UTF-8"); // Compléter le fonctionnement MAC BYTE [] text1 = mac.dofinal (texte); restring = new base64encoder (). EncodeBuffer (text1); restring = urlencoder.encode (reposring, "utf-8"); restring = restring.replace ("% 0a", ""); restring = restring.replace ("% 0d", ""); } catch (exception e) {e.printStackTrace (); } return reposring; } / ** * Téléchargez l'image recadrée * ZXIAO 2016/09/01 * * @param fileID * / public static String soumedCutedWebimage (Fichier multipartFile, String FileId, String x, String y, String w, String H) lance unpportEnCoDingException {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"}; // hauteur crop arrayList <string> listCrophEights = new ArrayList <string> (); listCrophEights.Add ("300"); int Cratel = Integer.ParseInt (x); // COMMOS X coordonnées int crropy = Integer.ParseInt (y); // Crop Y coordonnées // String [] CropFixs = new String [] {"L"}; // Image Crop Mark Set ArrayList <string> listCroPFixs = new ArrayList <String> (); listCropFix.Add ("L"); String Sourcesuffix = "JPG"; // Map Base suffixe String SourceFix = ""; // Base Map Logo / * boolean isResuffix = true; int hauteur = 1000; Int largeur = 750; String Mark = "T"; Mode de chaîne = "W"; * / / String url = signe (Cropurl) + "fileId =" + fileId + "& CropWidths =" + listCropWidths + "& cropheights =" + listCrophEights + "& Cropx =" + Cropx + "& crropy =" + crropy + "& cropFixs =" + listcropfixs + "& Sourcesuff =" + Sourcesuff + " "& SourceFix =" + sourceFix; System.out.println ("URL:" + URL); Httpurlconnection conn = null; OutputStream outstream = null; BufferedInputStream bin = null; try {bin = new BufferedInputStream (file.getInputStream ()); Conn = (httpurlConnection) Nouvelle URL (URL) .OpenConnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("Post"); Conn.SetDoOutput (true); // Conn.SetFixedLength StreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application / X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("Content-Length", file.getSize () + ""); // conn.setRequestProperty ("range", "bytes =" + ""); // Définissez le codage des caractères de HttpurlConnection Conn.SetRequestProperty ("Accept-Charset", "UTF-8"); outstream = conn.getOutputStream (); octet [] buf = nouveau octet [1024]; int len = 0; int lentcount = 0; while ((Len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok Lencount = LenCount + len; } int qui réponde = conn.getResponSECODE (); if (répondeCode == 200) {inputStream insiteam = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; } else {inputStream instream = Conn.getInputStream (); octet [] data1 = readAsByTearr (insideam); String json = new String (data1); instream.close (); retourner JSON; }} catch (exception e) {e.printStackTrace (); } enfin {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {e.printStackTrace (); }} return null; } / ** L'image doit être enregistrée localement après le téléchargement et le recadrage * ZXIAO 2016/09/01 * @param, * @param x * @param y * @param w * @param h * @return * @throws ioexception * / public static string soumedCroPiMage (Fichier multipartfile, lance x, entier y, Integer w, Integer H) Throws ioExet ant {INGER Y, INTERG dossier = System.getProperty ("java.io.tmpdir"); Fichier tempdir = nouveau fichier (dossier); // Si le dossier n'existe pas, créez si (! Tempdir .exists () &&! Tempdir .isdir ()) {// System.out.println ("// not not exists"); tempdir .mkdir (); } // chaîne de fichiers temporaire compressée srcpath = dossier + "scaletemp.jpg"; // Obtenez le suffixe du fichier / * fichier 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); * / // recadrer l'image cutimgutils o = new Cutimgutils (x, y, w, h); O.SetSrcPath (SrcPath); O.SetSUSBPath (dossier + "uptemp.jpg"); Fichier tempfile = o.cut ("jpg"); String s = soumimage (tempfile); retour s; } / ** * Obtenez la largeur de l'image téléchargée * ZXIAO 2016/09/09 * @param fichier * @return * / public static int getImgWidth (Fichier multipartFile) lève ioException {inputStream is = null; BufferedImage src = null; int ret = -1; try {is = file.getInputStream (); src = javax.imageio.imageio.read (is); ret = src.getWidth (null); // obtient la largeur d'image source est.close (); } catch (exception e) {e.printStackTrace (); } return ret; } / ** * Obtenez l'image téléchargée élevée * Zxiao 2016/09/09 * @param fichier * @return * / public static int getImgheight (fichier multipartFile) {inputStream is = null; BufferedImage src = null; int ret = -1; try {is = file.getInputStream (); src = javax.imageio.imageio.read (is); ret = src.GetHeight (null); // obtient la hauteur de l'image source est.close (); } catch (exception e) {e.printStackTrace (); } return ret; } / ** * Image d'échelle (mise à l'échelle par hauteur et largeur) * @param Objet de fichier de fichier * @param Adresse d'image de l'échelle du résultat * @param hauteur de hauteur hauteur * @param largeur d'échelle largeur * @param bb est-il nécessaire de remplir lorsque l'échelle est incorrecte: le vrai est un remplissage; Faux n'est pas rempli; * / Échelle de void statique publique (fichier multipartfile, résultat de la chaîne, hauteur int, largeur int, boolean bb) {try {double rapport = 0,0; // échelle / * CommonsMultiPartFile cf = (commonsMultuparTfile) fichier; DiskfileItem fi = (diskfileItem) cf.getFileItem (); Fichier f = fi.getStoreLocation (); * /// fichier f = nouveau fichier (srciagefile); InputStream inputStream = file.getInputStream (); BufferedImage BI = ImageIo.read (InputStream); Image item = bi.getScaledInstance (largeur, hauteur, bi.scale_smooth); // Calculez l'échelle if ((bi.getheight ()> height) || (bi.getWidth ()> width)) {if (bi.getheight ()> bi.getWidth ()) {ratio = (new Integer (height)). DoubleValue () / bi.GetHeight (); } else {ratio = (nouvel entier (largeur)). doubleValue () / bi.getWidth (); } AffinetRansformop OP = new AffineTransformop (affinetRansform .getScaleInstance (rapport, ratio), null); item = op.filter (bi, null); } if (bb) {// remplissage BufferedImage Image = new BufferedImage (largeur, hauteur, bufferedImage.type_int_rgb); Graphics2d g = image.creategraphics (); g.setColor (Color.white); G.Fillrect (0, 0, largeur, hauteur); if (width == item.getWidth (null)) g.DrawImage (itemp, 0, (height - item.getheight (null)) / 2, item.getWidth (null), item.getheight (null), colore.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) élément, "JPG", nouveau fichier (résultat)); } catch (ioException e) {e.printStackTrace (); }} public static void main (String [] args) {try {/ * file file = new File ("e: // bole // doc // service d'interface de service // interface de service bole Description v1.0.docx"); System.out.println ("file =" + file); String JSON = soumedFile (fichier); System.out.println ("json =" + json); * /} catch (exception e) {e.printStackTrace (); }}} Outils de recadrage d'images
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. java.io.fileInputStream; import java.io.ioException; import java.util.iterator; / ** * créé par l'administrateur sur 2016/9/1. * / classe publique CutImGutils {// === Le nom du chemin d'image source tel que: c: /1.jpg String privé SrcPath; // === Le nom du chemin de stockage d'image de clip. Par exemple: C: /2.jpg STRING PRIVATE STRING SUB-PATH; public void setsrcPath (String srcPath) {this.srcpath = srcPath; } public void setSubPath (String subpath) {this.subPath = subpath; } // === Point de tranche x coordonnée privée int x; privé int y; // === Largeur de point de glissade privé dans la largeur int; Hauteur d'int privé; public cutimgutils () {} public cutimgutils (int x, int y, int larget, int hauteur) {if (x <0) {x = 0; } else {this.x = x; } if (y <0) {y = 0; } else {this.y = y; } this.width = width; this.height = hauteur; } / ** * * Cramez l'image et enregistrez la nouvelle image après le recadrage. * / public File Cut () lève IOException {FileInputStream est = null; ImageInputStream iis = null; essayez {// lire les fichiers d'image est = new FileInputStream (srcPath); / ** * * Renvoie un itérateur contenant tous les ImageRereders actuellement enregistrés, qui prétendent pouvoir décoder le format spécifié. Paramètres: FormatName - contient le nom de format informel. * * (comme "jpeg" ou "tiff"), etc. * / iterator <ImageReader> it = imageo .getImageRedersByFormatName ("jpg"); ImageReRener Reader = it.next (); // Obtenez le flux d'image iis = imageo.CreateImageInputStream (IS); / ** * * <p> * iis: Lisez la source. Vrai: Recherchez uniquement * </p> *. Marquez-le comme «recherchez uniquement vers l'avant». * * Ce paramètre signifie que les images incluses dans la source d'entrée seront lues uniquement dans l'ordre, ce qui peut permettre au lecteur * * d'éviter la mise en cache de ces parties d'entrée contenant des données associées aux images de lecture précédemment. * / reader.setInput (iis, true); / ** * * <p> * classe qui décrit comment décoder les flux * <p> *. Utilisé pour spécifier comment convertir une image ou un ensemble d'images à partir d'un flux dans le contexte d'un framework I / O * * Java Image Image lors de la saisie. Plugin pour un format d'image spécifique * * * Une instance d'imageReadParam sera renvoyée de la méthode GetDefaulTreadParam d'Implémentation Implémentation Implémentation. * / ImageReadParam Param = Reader.getDefaulTreadParam (); / ** * * Zone de recadrage d'image. Le rectangle spécifie une zone dans l'espace de coordonnées, qui peut être définie par la coordonnée (x, y), la largeur et la hauteur du sommet supérieur gauche de l'objet rectangle **. * / Rectangle rect = nouveau rectangle (x, y, largeur, hauteur); // Fournit une tampon de tampon pour l'utiliser comme cible pour décoder les données de pixels. Param.SetSourceRegion (REct); / ** * Utilisez l'imageReadParam fourni pour lire l'objet spécifié en indexant ImageIndex et retournez * * en tant que tampon complet. * / BufferedImage Bi = Reader.read (0, param); // Enregistrer la nouvelle image imageo.write (BI, "JPG", nouveau fichier (sub-path)); File file = new File ("sub-path"); return fichier; } enfin {if (is! = null) is.close (); if (iis! = null) iis.close (); }} public File Cut (String Suffix) lève IOException {FileInputStream est = null; ImageInputStream iis = null; essayez {// lire le fichier image est = new FileInputStream (srcPath); // is = inputStream; / ** * Renvoie un itérateur contenant tous les ImageRereders actuellement enregistrés * * prétendant pouvoir décoder le format spécifié. Paramètres: FormatName - contient le nom de format informel. * * (comme "jpeg" ou "tiff"), etc. * iterator <ImageReader> it = imageo.getImageRedersByFormatName ("jpg"); * / String suffixName = null; if (suffixe.equals ("gif")) {suffixname = "gif"; } else if (suffix.equals ("png")) {suffixname = "png"; } else {suffixname = "jpg"; } Iterator <ImageReader> it = imageo .getImageRedersByFormatName (suffixName); ImageReRener Reader = it.next (); // Obtenez le flux d'image iis = imageo.CreateImageInputStream (IS); / ** * * <p> * iis: Lisez la source. Vrai: Recherchez uniquement * </p> *. Marquez-le comme «recherchez uniquement vers l'avant». * * Ce paramètre signifie que les images incluses dans la source d'entrée seront lues uniquement dans l'ordre, ce qui peut permettre au lecteur * * d'éviter la mise en cache de ces parties d'entrée contenant des données associées aux images de lecture précédemment. * / reader.setInput (iis, true); / ** * * <p> * classe qui décrit comment décoder les flux * <p> *. Utilisé pour spécifier comment convertir une image ou un ensemble d'images à partir d'un flux dans le contexte d'un framework I / O * * Java Image Image lors de la saisie. Plugin pour un format d'image spécifique * * * Une instance d'imageReadParam sera renvoyée de la méthode GetDefaulTreadParam d'Implémentation Implémentation Implémentation. * / 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之间相互转化
第一种方法:
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/.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。