Este artículo comparte un caso completo de cargar imágenes en Javaweb como referencia. El contenido específico es el siguiente
Ideas de implementación
• Use el complemento JCROP para recortar las coordenadas de la imagen en su teléfono
• Pase los parámetros recolectados al fondo, use objetos gráficos Java para dibujar imágenes para recortar
◦ Flujo de procesamiento de Background:
1. Comprima las imágenes cargadas en proporción y cárguelas al servidor de archivos, y guarde las imágenes comprimidas en un directorio temporal local.
2. Haga eco de la imagen comprimida en la página, use JCROP para recortar y recorte las coordenadas en el teléfono (x, y, ancho, altura)
■@paramx Clazo de destino COORDINADA DE PUNTO DE INTERENCIA X
■@Param y La coordenada del punto de partida de la porción de destino Y
■@Param Ancho de ancla
3. Procesamiento detrás del escenario de cultivo y carga
página de JSP
< %@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> < %@ página contentType = "text/html; charset = utf-8" lenguaje = "java" %> <! doctype html> <html> <fead> <sead> contenido = "text/html; charset = utf-8"/> <title> cargue el usuario avatar </title> <link href = "$ {pageContext.request.contextpath} /js/cutimg/css/master.css" rel = "Stylesheet"/> <linkin href = "$ {PageContext.Request.ContextPath} /js/cutimg/css/upload.css" rel = "stylesheet"/> <link href = "$ {pageContext.request.contextpath} /js/cutimg/css/jquery.rollBar.csss" rel = "stylesheet"/> <link href = "$ {pageContext.request.contextPath} /js/cutimg/css/jquery.jcrop.css" rel = "styleshet"/> </head> <body> <liv> <form id = "uploadimgFrom" Inctype = "Multipart/Form-data" <Div> <div> <div> <div> <div id = "pic2"> <div id = "uploadfile"> <div style = "margin-left: 75px;"> <a href = "javaScript :;" id = "Uptext" style = "color: rojo;"> cargar avatar </a> </div> <p> admite formats jpg y png <br/> imagen menos que 2m </p> </div> <!-return to mosswell ninguno; "> <a href =" javascript :; " style = "Color: Red"> Reupload </a> </p> <input type = "Hidden" name = "picval" id = "picval" /> <input type = "Hidden" name = "OrigpicVal" id = "Origpicval" valor = "" /> <input type = "Hidden" name = "temporigpic" id = "temporigpic" /> <input type " name = "fileid" id = "fileid" size = "100" /> <input type = "Hidden" name = "fileurl" id = "fileurl" size = "100" /> <input type = "hidden" name = "imgheight" id = "imgHeight" size = "100" /> <input type = "hidden" name = "imgwidth" id = "imgwwwwwwwwwwwWidth" size "100" 100 "100" </div> <div> <img id = "preview_1" src = "$ {pageContext.request.contextpath} /Images/4-3.jpg"/> </div> <p> 400 x 300 píxeles </p> <%-<div> <img id = "preview_2" src = $ {PageContext.Request.ContextPath} /Images/4-3.jpg/> </div> <p> 80 x 80 píxeles </p>-%> <p> drag o zoom para generar un avatar satisfactorio </p> </div> <%-<div ide = "img_description"> <xtexarea </divitar> id = "Upalert"> </font> </div> </div> </div> <input type = "Hidden" name = "x" 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"/> <input type = "Hidden" name = "imgid" id = "imgid"/> <div> <div id = "saveImage"> <a href = "javaScript :;" style = "Color: Red"> Save Avatar </a> </div> </iv> </form> </div> </body> <script type = "text/javascript" src = "$ {pageContext.request.contextpath} /js/jquery.form.js"> </script> <script type = "text/javascript" "" "" src = "$ {PageContext.Request.ContextPath} /js/jquery.validate.min.js"> </script> <script type = "text/javaScript" src = "$ {pageContext.request.contextpath} /js/check.js"> </script> <script type = "text/jaxitt" src = "$ {PageContext.Request.ContextPath} /js/check.js"> </script> <script src = "$ {pageContext.request.contextPath} /js/cutimg/js/jquery-1.7.1.Min.js type =" Text/javascript " src = "$ {PageContext.Request.ContextPath} /js/cutimg/js/jquery.form.js" type = "text/javascript"> </script> <script src = "$ {pageContext.request.contextpath} /js/cutimg/js/jquery-custom-filom-filom-filoms type = "text/javascript"> </script> <script src = "$ {pageContext.request.contextpath} /js/cutimg/js/jquery-custom-file-input.js" type = "text/javascript"> </script> <scry src = "$ {pageContext.request.contextpath} /js/cutimg/js/jquery.jcRrop.js" type = "text/javascript"> </script> <script src = "$ {pageContext.request.contextpath} /js/cutimg/js/jquer.rollbar.jar.jsbar.jjar.jjar.jjar.jlor.jlor.jlor.jlor.jlor.jlor.jlor.jlor.jlor.joro. 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; // cajero de selección de cajas de selección. ["200", "80"]; // La matriz de "ancho de la imagen" ancho ", defina el ancho de diferentes imágenes de grandes a pequeños de acuerdo con el número de imágenes // fotos.heights = [" 200 "," 80 "]; // el tamaño de imagen" alto "matriz, define la altura de diferentes imágenes grandes a pequeñas según el número de fotos de las fotos. Photos.upload_filetextid = "Uptext"; // Cargar el botón Componente ID de texto de texto "OriginalImg"; // Photos de ID de imagen base. "fileUrl"; /// cargue la imagen url fotos.upload_picimgheight = "imgheight"; // la imagen base cargada de fotos alta. Photos.upload_originValueId = "OrigpicVal"; // La identificación de contenido de imagen original cuando otras páginas ingresan fotos.upload_rollbarid = "pic2"; // ID de scrollbar personalizados Múltiples imágenes pequeñas de diferentes tamaños, el formato de identificación de múltiples imágenes pequeñas "prefijo" + número (a partir de 1), ejemplo: id = "Photos_preview1" ... Photos.ParentFileMgid = "Imgurl"; // Control de imagen principal ID Photos.ParentFilEvalueId = "imgid"; //: la dirección de la imagen de la imagen ID de control de la imagen. = "w"; // w photos.hid = "h"; // h Photos.uptext_format = "Lo siento, solo los formatos jpg, png y BMP son compatibles con el tiempo de tiempo"; // verificación de formato de imagen text/*photos.uptext_size = "Lo siento, el tamaño de imagen no puede exceder 2m";*// tamaños de imagen verificación text/*fotos.upt_error = "Image de carga de imagen"; Text*/Photos.url_check = "/Enterprise/FilesCheck"; // Dirección Photos.Url_upload = "/Enterprise/uploadPhoto? Up = original"; // cargar imagen de imagen Carga de imagen base guardado </script> </html>Código Java de fondo
Herramienta de carga de imágenes
paquete com.shengya.service.utils; import com.shengya.service.imgContants; import org.apache.commons.fileupload.disk.diskfileitem; import org.springframework.web.multipart.multipartfile; import; org. javax.Imageio.ImagerAdParam; import java.awt.*; import java.awt.geom.affinetransform; import java.awt.image.affinetransformop; import java.awt.image.bufferedImage; import java.io.*; import java.net.net.httpurlconnection; import java.net; importación; importación; importación; java.net.urlencoder; import java.util.arrayList;/** * @author Darcy * creado por administrador el 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?"; Cadena estática final pública vudioUrl = imgContants.file_upload + "/file/uploadfile?"; Public Final Static String CropUrl = imgContants.img_upload + "/file/recopImage?"; byte estático privado [] readAsByTearr (inputStream is) {bytearRaReAutputStream Baos = new byteArRaReOutputStream (); intente {byte [] bytes = new byte [1024]; int longitud = 0; while ((longitud = is.read (bytes))! = -1) {baos.write (bytes, 0, longitud); } return baos.tobytearray (); } catch (Exception e) {E.PrintStackTrace (); } finalmente {try {baos.close (); } catch (ioException e) {E.PrintStackTrace (); }} return null; } / ** * cargar imagen * * @param archivo * / public static string SubmitImage (archivo de archivo) lanza UnspportedEnCodingException {String filename = urlencoder.enCode (file.getName (), "utf-8"); Long filesize = file.length (); booleano isresuffix = true; int altura = 0; int ancho = 500; String mark = "t"; Modo de cadena = "W"; String url = firm (url) + "& canalNo = muying_android" + "& filename =" + filename + "& silesize =" + filesize + "& isresuffix =" + isresuffix + "& hight =" + hight + "& width =" + width + "& mark =" + mark + "& mode =" + modo; System.out.println ("url:" + url); Httpurlconnection conn = null; OutputStream OutStream = null; BufferedInputStream bin = null; intente {bin = new BufferedInputStream (nuevo FileInputStream (File)); conn = (httpurlconnection) nueva url (url) .openconnection (); Conn.SetConnectTimeOut (15000); Conn.setRequestMethod ("Post"); Conn.setDoOutput (verdadero); // conn.setfixedLengthstreamingMode (file.length ()); conn.setRequestProperty ("Content-type", "Application/X-WWW-form-URLEncoded"); conn.setRequestProperty ("Content-Length", file.length () + ""); // conn.setRequestProperty ("rango", "bytes ="+""); // Establezca la codificación de caracteres de httpurlconnection conn.setRequestProperty ("Acept-Charset", "UTF-8"); Outstream = Conn.getOutputStream (); byte [] buf = nuevo byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok lencount = lencount + len; } outstream.flush (); int ResponseCode = conn.getResponseCode (); if (ResponseCode == 200) {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; } else {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; }} catch (Exception e) {E.PrintStackTrace (); } finalmente {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } / ** * cargar imagen * * @param archivo * / public static string SubtWebImage (archivo multipartfile) lanza UnsupportedEncodingException {String filename = urlencoder.enCode (file.getOriginalFileName (), "UTF-8"); Long filesize = file.getSize (); booleano isresuffix = true; int altura = 0; int ancho = 500; String mark = "t"; Modo de cadena = "W"; String url = firm (url) + "& canalNo = muying_android" + "& filename =" + filename + "& silesize =" + filesize + "& isresuffix =" + isresuffix + "& hight =" + hight + "& width =" + width + "& mark =" + mark + "& mode =" + modo; System.out.println ("url:" + url); Httpurlconnection conn = null; OutputStream OutStream = nulo; BufferedInputStream bin = null; intente {bin = new BufferedInputStream (file.getInputStream ()); conn = (httpurlconnection) nueva url (url) .openconnection (); Conn.SetConnectTimeOut (15000); Conn.setRequestMethod ("Post"); Conn.setDoOutput (verdadero); // conn.setfixedLengthstreamingMode (file.length ()); conn.setRequestProperty ("Content-type", "Application/X-WWW-form-URLEncoded"); conn.setRequestProperty ("Content-Length", file.getSize () + ""); // conn.setRequestProperty ("rango", "bytes ="+""); // Establezca la codificación de caracteres de httpurlconnection conn.setRequestProperty ("Acept-Charset", "UTF-8"); Outstream = Conn.getOutputStream (); byte [] buf = nuevo byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok lencount = lencount + len; } outstream.flush (); int ResponseCode = conn.getResponseCode (); if (ResponseCode == 200) {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; } else {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; }} catch (Exception e) {E.PrintStackTrace (); } finalmente {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } / ** * Subir video * * @param archivo * / public static string SubmitRadio (archivo multipartfile) lanza la excepción {String url = signRadio (radiourl); System.out.println ("url:" + url); Httpurlconnection conn = null; OutputStream OutStream = null; BufferedInputStream bin = null; intente {bin = new BufferedInputStream (file.getInputStream ()); conn = (httpurlconnection) nueva url (url) .openconnection (); Conn.SetConnectTimeOut (15000); Conn.setRequestMethod ("Post"); Conn.setDoOutput (verdadero); conn.setRequestProperty ("Content-type", "Application/X-WWW-form-URLEncoded"); conn.setRequestProperty ("Content-Length", file.getSize () + ""); Conn.setRequestProperty ("Acept-Charset", "UTF-8"); Outstream = Conn.getOutputStream (); byte [] buf = nuevo byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok lencount = lencount + len; } outstream.flush (); int ResponseCode = conn.getResponseCode (); if (ResponseCode == 200) {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; } else {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; }} catch (Exception e) {E.PrintStackTrace (); } finalmente {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } /** * Sube la instantánea de currículum * * @Param FileName * @param Content * @return * @throws UnsupportedEncodingException * /public static String SubtitFile (String FileName, String Content) lanza UnspportedEnDENDINGException {// content = urlencoder.Encode (contenido, "); FileName = urlencoder.Encode (nombre de archivo, "UTF-8"); byte [] contentBytes = content.getBytes (); Long filesize = ContentBytes.Length; booleano isresuffix = true; int altura = 0; int ancho = 500; String Mark = "T"; Modo de cadena = "W"; Cadena url = sign (fileUrl) + "& canalNo = muying_android" + "& filename =" + filename + "& filesize =" + filesize + "& isresuffix =" + isresuffix + "& hight =" + hight + "& width =" + width + "& mark =" + mark + " + mode =" mode; System.out.println ("url:" + url); Httpurlconnection conn = null; OutputStream OutStream = nulo; BufferedInputStream bin = null; intente {conn = (httpurlconnection) new url (url) .openconnection (); Conn.SetConnectTimeOut (15000); Conn.setRequestMethod ("Post"); Conn.setDoOutput (verdadero); // conn.setfixedLengthstreamingMode (file.length ()); conn.setRequestProperty ("Content-type", "Application/X-WWW-form-URLEncoded"); Conn.setRequestProperty ("Content-Length", content.length () + ""); // conn.setRequestProperty ("rango", "bytes ="+""); // Establezca la codificación de caracteres de httpurlconnection conn.setRequestProperty ("Acept-Charset", "UTF-8"); Outstream = Conn.getOutputStream (); Outstream.Write (ContentBytes, 0, ContentBytes.Length); // ok outStream.flush (); int ResponseCode = conn.getResponseCode (); if (ResponseCode == 200) {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; } else {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; }} catch (Exception e) {E.PrintStackTrace (); } finalmente {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } / *** cargar adjunto** @return json cadena* @throws UnsupportedEncodingException* / public static string SubtitFile (archivo multipartfile) lanza UnsupportedEncodingException {String fileName = urlencoder.enCode (file.getOriginalFileName (), "utf-8"); Long filesize = file.getSize (); booleano isresuffix = true; int altura = 0; int ancho = 500; String Mark = "T"; Modo de cadena = "W"; Cadena url = sign (fileUrl) + "& canalNo = muying_android" + "& filename =" + filename + "& filesize =" + filesize + "& isresuffix =" + isresuffix + "& hight =" + hight + "& width =" + width + "& mark =" + mark + " + mode =" mode; System.out.println ("url:" + url); Httpurlconnection conn = null; OutputStream OutStream = nulo; BufferedInputStream bin = null; intente {bin = new BufferedInputStream (file.getInputStream ()); conn = (httpurlconnection) nueva url (url) .openconnection (); Conn.SetConnectTimeOut (15000); Conn.setRequestMethod ("Post"); Conn.setDoOutput (verdadero); // conn.setfixedLengthstreamingMode (file.length ()); conn.setRequestProperty ("Content-type", "Application/X-WWW-form-URLEncoded"); conn.setRequestProperty ("Content-Length", file.getSize () + ""); // conn.setRequestProperty ("rango", "bytes ="+""); // Establezca la codificación de caracteres de httpurlconnection conn.setRequestProperty ("Acept-Charset", "UTF-8"); Outstream = Conn.getOutputStream (); byte [] buf = nuevo byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok lencount = lencount + len; } int ResponseCode = conn.getResponseCode (); if (ResponseCode == 200) {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; } else {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; }} catch (Exception e) {E.PrintStackTrace (); } finalmente {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } signo de cadena estática privada (String BaseUrl) lanza UnspportedEncodingException {Long Currency = System.CurrentTimemillis (); marca de tiempo larga = moneda / 1000; String data = "ActionName = uploadImage" + "& SecretKey = 4B19F08DBF0ADB82CE9CC7C207EC1DC9" + "& timestamp =" + timestamp; String Signature = HMAC_SHA1 ("4B19F08DBF0ADB82CE9CC7C207EC1DC9", URLENCODER.ENDODE (DATA, "UTF-8")); firma = firma.replace ("%3d", "%3d"); firma = firma.replace ("%3a", "%3a"); firma = firma.replace ("%2f", "%2f"); return BaseUrl + Data + "& Signature =" + Signature; } cadena estática privada SignRadio (URL de cadena) lanza la excepción {Long CurrenceBttime = System.CurrentTimemillis (); String data = "SecretKey = F1B79C865C424BE46183A2F0A49A0F15" + "& timestamp =" + moneda; System.out.println ("url:" + url + data); System.out.println ("url =" + urlencoder.enCode (url + data, "UTF-8")); String Signature = HmacSha1util.getSignature (urlencoder.Encode (URL + datos, "UTF-8"), "F1B79C865C424BE46183A2F0A49A0F15"); Return URL + Data + "& Signature =" + Signature; } cadena estática privada HMAC_SHA1 (tecla de cadena, datos de cadena) {String Restring = ""; Pruebe {datas = dataS.replace ("%3a", "%3a"); datas = dataS.replace ("%2f", "%2f"); datas = dataS.replace ("%3d", "%3d"); byte [] data = key.getBytes ("UTF-8"); // Construye una clave basada en la matriz de bytes dada, y el segundo parámetro especifica el nombre de un algoritmo clave SecretKey SecretKey = New SecretKeySpec (Data, "HMACSHA1"); // Generar un objeto MAC con el algoritmo MAC especificado Mac = Mac.getInstance ("HMACSHA1"); // Inicializar el objeto Mac con la clave dada Mac.init (SecretKey); byte [] text = dataS.getBytes ("UTF-8"); // Complete Mac Operation Byte [] Text1 = Mac.Dofinal (texto); Restring = new Base64Encoder (). CodeBuffer (Text1); restring = urlencoder.Encode (Restring, "UTF-8"); Restring = Restring.replace ("%0a", ""); Restring = Restring.replace ("%0d", ""); } catch (Exception e) {E.PrintStackTrace (); } return Restring; }/** * Sube la imagen recortada * ZXIAO 2016/09/01 * * @param fileId */public static string SENTITTCUTEDWEBImage (archivo multipartfile, string fileId, string x, string y, string w, string h) lanza no comportedEncodingException {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 [] crotheights = new String [] {"50"}; // Crop Highting ArrayList <String> listCropheights = new ArrayList <String> (); listCropheights.Add ("300"); int Cropx = Integer.ParseInt (x); // Crop X Coordinate int Cropy = Integer.ParseInt (y); // Crop Y Coordinates // String [] CropFixs = new String [] {"l"}; // Crop Imagen Mark Set ArrayList <String> ListCropfixs = New ArrayList <String> (); listCropfixs.Add ("L"); String SourceSuffix = "JPG"; // SUFFIX MAP BASE String SourceFix = ""; // logotipo de mapa base/* boolean isresuffix = true; int altura = 1000; Intenio int = 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 = nulo; BufferedInputStream bin = null; intente {bin = new BufferedInputStream (file.getInputStream ()); conn = (httpurlconnection) nueva url (url) .openconnection (); Conn.SetConnectTimeOut (15000); Conn.setRequestMethod ("Post"); Conn.setDoOutput (verdadero); // conn.setfixedLengthstreamingMode (file.length ()); conn.setRequestProperty ("Content-type", "Application/X-WWW-form-URLEncoded"); conn.setRequestProperty ("Content-Length", file.getSize () + ""); // conn.setRequestProperty ("rango", "bytes ="+""); // Establezca la codificación de caracteres de httpurlconnection conn.setRequestProperty ("Acept-Charset", "UTF-8"); Outstream = Conn.getOutputStream (); byte [] buf = nuevo byte [1024]; int len = 0; int lencount = 0; while ((len = bin.read (buf))! = -1) {outstream.write (buf, 0, len); // ok lencount = lencount + len; } int ResponseCode = conn.getResponseCode (); if (ResponseCode == 200) {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; } else {InputStream InSteam = conn.getInputStream (); byte [] data1 = readAsByTearr (InSteam); Cadena json = nueva cadena (data1); Intileam.close (); regresar json; }} catch (Exception e) {E.PrintStackTrace (); } finalmente {try {if (outstream! = null) {outstream.close (); }} catch (ioException e) {E.PrintStackTrace (); }} return null; } /**The image needs to be saved locally after uploading and cropping*zxiao 2016/09/01 * @param , * @param x * @param y * @param w * @param h * @return * @throws IOException */ public static String submitCropImage(MultipartFile file,Integer x,Integer y,Integer w,Integer h) throws IOException { String carpeta = system.getProperty ("java.io.tmpdir"); Archivo tempDir = nuevo archivo (carpeta); // Si la carpeta no existe, cree if (! TempDir .Exists () &&! TempDir .IsDir ()) {// System.out.println ("// no existe"); tempdir .mkdir (); } // cadena de archivo temporal comprimido srcpath = carpeta+"scaletemp.jpg"; // Obtenga el sufijo del archivo/*archivo uploadFile = nuevo archivo (srcpath); InputStream InputStream = file.getInputStream (); FileInputStream fs = (fileInputStream) inputStream; String srcimg = urlencoder.encode (file.getoriginalFileName (), "UTF-8"); String Suffix = srcimg.substring (srcimg.lastindexof (".")+1);*// recorte la imagen cutimgutils o = new cutimgutils (x, y, w, h); O.SetSrcpath (srcpath); O.SetSubpath (carpeta+"uptemp.jpg"); Archivo tempfile = o.cut ("jpg"); Cadena S = SubtITEMage (tempfile); regreso s; }/** * Obtenga el ancho de la imagen cargada * ZXIAO 2016/09/09 * @param archivo * @return */public static int BufferedImage src = null; int ret = -1; try {is = file.getInputStream (); src = javax.imageio.imageio.read (is); ret = src.getWidth (nulo); // Obtener el ancho de la imagen de origen IS.Close (); } catch (Exception e) {E.PrintStackTrace (); } return ret; }/** * Obtenga la imagen cargada High * Zxiao 2016/09/09 * @param archivo * @return */public static int BufferedImage src = null; int ret = -1; try {is = file.getInputStream (); src = javax.imageio.imageio.read (is); ret = src.getheight (nulo); // Obtener la altura de la imagen de origen IS.Close (); } catch (Exception e) {E.PrintStackTrace (); } return ret; } /*** Imagen de escala (escala por altura y ancho)* @param Archivo de archivo Objeto* @param Resultado Imagen de escala Dirección* @param Altura de escala Altura* @param Ancho de escala de ancho* @param BB ¿Es necesario completar cuando la escala es incorrecta: verdadero es un relleno; Los falsos no se llenan; */ escala de voides estatices public (archivo multipartfile, resultado de cadena, intdipt, int width, boolean bb) {try {doble relación = 0.0; // escalar/*commonsMultipartFile cf = (commonsMultipartFile) archivo; Diskfileitem fi = (diskfileitem) cf.getFileItem (); Archivo f = fi.getstorelocation ();*/// archivo f = nuevo archivo (srcImageFile); InputStream InputStream = file.getInputStream (); BufferedImage bi = imageIO.read (inputStream); Imagen elemento = bi.getScaledInstance (ancho, altura, bi.scale_smooth); // Calcule la escala if ((bi.getheight ()> altura) || (bi.getwidth ()> width)) {if (bi.getheight ()> bi.getwidth ()) {ratio = (nuevo entero (altura)). Doublevalue () / bi.getheight (); } else {ratio = (nuevo entero (ancho)). doubleValue () / bi.getWidth (); } Affinetransformop op = new Affinetransformop (affinetransform .getScaleInstance (relación, relación), nulo); item = op.filter (bi, nulo); } if (bb) {// relleno bufferedimage image = new BufferedImage (ancho, altura, bufferedImage.type_int_rgb); Graphics2d g = image.createGraphics (); G.SetColor (color.white); G.Fillrect (0, 0, ancho, altura); if (width == item.getWidth (null)) G.DrawImage (itemp, 0, (altura - item.getheight (null)) / 2, item.getwidth (null), item.getheight (null), color.white, null); más G.DrawImage (itemp, (ancho - item.getWidth (null)) / 2, 0, item.getWidth (null), item.getheight (null), color.white, null); G.Dispose (); elemento = imagen; } ImageIO.Write ((BufferedImage) elemento, "jpg", nuevo archivo (resultado)); } catch (ioException e) {E.PrintStackTrace (); }} public static void main (string [] args) {try {/* archivo archivo = nuevo archivo ("e: // bole // doc // interfaz de servicio documento // interfaz de servicio de bolas descripción v1.0.docx"); System.out.println ("file =" + archivo); String json = SubtitFile (archivo); System.out.println ("json =" + json);*/} Catch (Exception e) {E.PrintStackTrace (); }}} Herramientas de recorte de imágenes
paquete com.shengya.service.utils; import javax.imageio.Imageio; import javax.imageio.imagereadparam; import javax.imageio.iMageReader; import javax.imageio.stream.imageInputputputputs; import java.aw.*; import java.awt.image.bufferedimageMageMage; java.io.fileInputStream; import java.io.ioexception; import java.util.iterator;/*** creado por el administrador el 2016/9/1. */public class cutImGutils {// === El nombre de la ruta de la imagen de origen como: c: /1.jpg private string srcpath; // === Nombre de la ruta de almacenamiento de la imagen del clip. Por ejemplo: C: /2.jpg Subpath de cadena privada; public void setSrcpath (string srcpath) {this.srcpath = srcpath; } public void setSubpath (String Subpath) {this.subpath = subpath; } // === Punto de corte x coordenada private int x; privado int y; // === Slift Point Ancho Private int Ancho; Altura privada int; public CutimGUtils () {} public cutImGutils (int x, int y, int width, int hight) {if (x <0) {x = 0; } else {this.x = x; } if (y <0) {y = 0; } else {this.y = y; } this.width = width; this.Height = altura; } /** * * recorte la imagen y guarde la nueva imagen después del recorte. */ public File Cut () lanza IOException {fileInputStream is = null; ImageInputStream iis = null; intente {// leer archivos de imagen IS = new FileInputStream (srcpath); /** * * Devuelve el iterador que contiene todos los imágenes de imágenes registradas actualmente, que afirman poder decodificar el formato especificado. Parámetros: FormatName: contiene el nombre del formato informal. * * (como "JPEG" o "TIFF"), etc. */ Iterator <Iriceroader> it = ImageIO .GetImageReadersByFormatName ("jpg"); ImageReader lector = it.next (); // Obtener la transmisión de la imagen iis = imageIO.CreateEmageInputStream (is); /** * * <p> * IIS: lea la fuente. VERDADERO: busque solo hacia adelante * </p> *. Marquelo como 'buscar solamente hacia adelante'. * * Esta configuración significa que las imágenes incluidas en la fuente de entrada se leerán solo en orden, lo que puede permitir que el lector * * evite almacenar en caché las porciones de entrada que contienen datos asociados con imágenes de lectura previamente. */ lector.setInput (iis, true); /** * * <p> * Clase que describe cómo decodificar las secuencias * <p> *. Se utiliza para especificar cómo convertir una imagen o un conjunto de imágenes de una transmisión en el contexto de un marco de I/O * * de imagen Java cuando se ingresa. Plugin para un formato de imagen específico * * * Una instancia de ImageReadParam se devolverá desde el método GetDefaultreadParam de su implementación de ImageReader. */ ImagereadParam Param = Reader.getDefaulTreadParam (); /** * * Área de cultivo de imágenes. El rectángulo especifica un área en el espacio de coordenadas, que puede definirse por la coordenada (x, y), el ancho y la altura del vértice superior izquierdo del objeto rectángulo **. */ Rectangle rect = nuevo rectángulo (x, y, ancho, altura); // Proporcione una BufferedImage para usarlo como objetivo para decodificar los datos de píxeles. param.setSourCeregion (RECT); /** * Use el ImageReDParam proporcionado para leer el objeto especificado indexando ImageIndex y return * * como una BufferedImage completa. */ Bufferedimage bi = lector.read (0, param); // Guardar nueva imagen ImageIO.Write (BI, "JPG", nuevo archivo (Subpath)); Archivo archivo = nuevo archivo ("subpath"); Revolver archivo; } finalmente {if (is! = null) is.close (); if (iis! = null) iis.close (); }} Public File Cut (String Sufix) lanza ioexception {fileInputStream is = null; ImageInputStream iis = null; Pruebe {// Leer el archivo de imagen IS = nuevo FileInputStream (srcpath); // is = inputStream; /** * Devuelve el iterador que contiene todos los imágenes de imágenes registradas actualmente * * que afirman poder decodificar el formato especificado. Parámetros: FormatName: contiene el nombre del formato informal. * * (como "jpeg" o "tiff"), etc. * iterator <Iriceroader> it = imageIO.GetImagerArEadersByFormatName ("jpg"); */ String sufreMname = null; if (sufix.equals ("gif")) {suffixname = "gif"; } else if (suffix.equals ("png")) {suffixname = "png"; } else {suffiXName = "jpg"; } Iterator <Iriceroader> it = imageIO .getImagreeReadersByFormatName (sufreMName); ImageReader lector = it.next (); // Obtener la transmisión de la imagen iis = imageIO.CreateEmageInputStream (is); /** * * <p> * IIS: lea la fuente. VERDADERO: busque solo hacia adelante * </p> *. Marquelo como 'buscar solamente hacia adelante'. * * Esta configuración significa que las imágenes incluidas en la fuente de entrada se leerán solo en orden, lo que puede permitir que el lector * * evite almacenar en caché las porciones de entrada que contienen datos asociados con imágenes de lectura previamente. */ lector.setInput (iis, true); /** * * <p> * Clase que describe cómo decodificar las secuencias * <p> *. Se utiliza para especificar cómo convertir una imagen o un conjunto de imágenes de una transmisión en el contexto de un marco de I/O * * de imagen Java cuando se ingresa. 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之间相互转化
El primer método:
MultipartFile file = xxx; CommonsMultipartFile cf= (CommonsMultipartFile)file; DiskFileItem fi = (DiskFileItem)cf.getFileItem(); File f = fi.getStoreLocation();
会在项目的根目录的临时文件夹下生成一个文件;
El segundo método:
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); // 得到源图宽
Referencias:
jcop api:http://code.ciaoca.com/jquery/jcrop/.
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.