Este artigo compartilha um caso completo de fazer upload de imagens no Javaweb para referência. O conteúdo específico é o seguinte
Idéias de implementação
• Use o plug -in jcrop para prender as coordenadas da imagem no seu telefone
• Passe os parâmetros coletados para o plano de fundo, use objetos gráficos Java para desenhar imagens para cortar
◦ Fluxo de processamento de background:
1. Compressa as imagens enviadas em proporção e envie -as para o servidor de arquivos e salve as imagens compactadas em um diretório temporário local.
2. Ecoe a imagem compactada na página, use o JCROP para cortar e prenda as coordenadas no telefone (x, y, largura, altura)
■@paramx Target Slice Start Point Coordenine X
■@param y O ponto de partida da fatia de destino coordenar Y
■@param width alvo slice width ■@param altura altura altura da fatia
3. Processamento dos bastidores de corte e upload
Página JSP
< %@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> < %@ página contenttype = "text/html; charset = utf-8" idioma = "java" %> <! Content = "Texto/html; charset = utf-8"/> <title> Carregar Avatar do usuário </ititure> <link href = "$ {PageContext.request.ContextPath} /js/cutimg/css/master.css" rel = "Stylesheet"/> <link href="${pageContext.request.contextPath}/js/cutImg/css/upload.css" rel="stylesheet" /> <link href="${pageContext.request.contextPath}/js/cutImg/css/jquery.rollbar.css" rel="stylesheet" /> <link href = "$ {pageContext.request.ContextPath} /js/cutimg/css/jquery.jcrop.css" rel = "stylesheet"/> </head> <body> <div> <dorm> <form = "uploadImgfrom" "Enctype =" Metod/Metod/Metod/Metodsat> <body> <div> <form id = "uploadImgfrom" "Enctype =" "Metod/Metod/Metod/Metodsat> <div id = "pic2"> <div id = "uploadfile"> <div style = "margin-left: 75px;"> <a href = "javascript :;" id = "uptext" style = "cor: vermelho;"> carregar avatar </a> </div> <p> suportar formatos jpg e png <br/> imagem menos de 2m </p> </div> <!-retornar para exibir fotos-> <img src = "" name = "Í Í -od" ÍDO "ORIGINIMG"/> nenhum; "> <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 = "imgwidth" idghid = "100" /> <input type = "hidden" = "imgwidth" ids = "100" /> <input " id = "visuriew_1" src = "$ {PageContext.Request.ContextPath} /images/4-3.jpg"/> </div> <p> 400 x 300 pixels </p> <%-<div> <mg id = "visiew_2" src = $ {{ </div> <p> 80 x 80 pixels </p>-%> <p> arrastar ou zoom para gerar um avatar satisfatório </p> </div> <%-<div id = "img_description"> <texttarea </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 =" hidd "name =" iMgurl "=" impirl " /> <sput" /"hind" hidd = "imguld" = "impirl" /> <input "" hidd "hidd =" iMgurl "=" impirl " /> <input" <div> <div id = "saveImage"> <a href = "javascript:;" style = "cor: vermelho"> salve avatar </a> </div> </div> </morm> </div> </body> <script type = "text/javascript" src = "$ {PageContext.request.ContextPath} /js/jquery.form.js"> </script> src = "$ {PageContext.request.ContextPath} /js/jquery.validate.min.js"> </script> <script type = "text/javascript" src = "$ {pageContext.request.ContextPath} /js/check.js">> src = "$ {PageContext.request.ContextPath} /js/check.js"> </script> <script src = "$ {PageContext.request.Contextpath} /js/cutimg/jquerycerd-cretd.1/ 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"> </cript> <cript 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.minmin.js" type = "text/javascript"> </script> <cript 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"> photos.jcorpwidth = 400; // Crop Sereção de seleção de fotos photos.jcorpheight = 3; "80"]; // Array da largura do tamanho da imagem, defina a largura de imagens diferentes de grande a pequena, de acordo com o número de fotos // fotos.Heights = ["200", "80"]; // o tamanho da imagem "alto", define a altura de uplroadfillefillefillefillefillefillefillefillefillefillefillefil, de acordo com o número de fotos. photos.upload_fileTextId = "uptext"; // Carregar o botão do componente ID do texto fotos.upload_alertId = "upalert"; // idézio de texto photos.upload_alertclassname = "error"; // o estilo de texto imediato. "Originalimg"; // Imagem base ID Photos.upload_reloadid = "up_reload"; // REOPLOAD ID do componente fotos.upload_picValueId = "picval"; // upload O ID do conteúdo da imagem inferior.UPLOAD_PICFILEAD = "FILEID"; //// UPLOUGE O ID da imagem a imagem url photos.upload_picimghight = "imgheight"; // a imagem base carregada alta fotos.upload_picimgwidth = "imgwidth"; // a imagem de base uploada Photos larga.upload_temporiginValueId = "Temporigpic Photos; // O ID da imagem original quando o conteúdo da imagem é o conteúdo da imagem original. "Origpicval"; // O ID de conteúdo da imagem original quando outras páginas insere fotos.upload_rollbarid = "pic2"; // Photos de identificação de scrollbar de scrollbar "prefixo" + número (a partir de 1), exemplo: id = "photos_preview1" ... fotos.parentfileImgid = "imgurl"; // control de imagem pai photos.parentfileValueId = "imgid"; // picture time control picture photos.xid = "x" // x photos.yid = "y"; "h"; // h fotos.uptx_format = "Desculpe, apenas os formatos JPG, PNG e BMP são suportados por enquanto"; // Formato de imagem Texto de verificação/*photos.uptxt_size = "Desculpe, o tamanho da imagem não pode exceder 2m"; "/Enterprise/filesCheck"; // Endereço fotos.url_upload = "/Enterprise/uploadphoto?Código Java de Background
Ferramenta de upload de imagem
pacote com.shengya.service.utils; importar com.shengya.service.imgcontants; importar org.apache.commons.fileupload.disk.diskfileitem; importar org.springframework.web.multipart.multipartFile; org.springframework.web.multipart.commons.commonsmultipartFile; importar sun.misc.base64Encoder; importar javax.crypto.mac; importImection.crypto.secretKey; import javax.crypto.sec.secretkeyspec; javax.Imageio.IMAGEEADPARAM; importar java.awt.*; importar java.awt.geom.affineTransform; importar java.awt.image.affineTransformOp; import java.awt.Image.BufferedImage; import java.io.*;; java.net.urlencoder; importar java.util.ArrayList;/** * @Author Darcy * criado pelo administrador em 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 estático string url = imgcontants.img_upload + "/file/uploadImage?"; public final static string fileurl = imgcontants.img_upload + "/file/uploadfile?"; Public final Static String Vediourl = imgContants.file_upload + "/file/uploadfile?"; public final Static String CropUrl = imgContants.img_upload + "/file/cropImage?"; byte estático privado [] readasbyTearr (inputStream is) {bytearrayoutputStream baos = new ByteArrayOutputStream (); tente {byte [] bytes = novo byte [1024]; int length = 0; while ((comprimento = is.read (bytes))! = -1) {baos.write (bytes, 0, comprimento); } return baos.tobytearray (); } catch (Exceção e) {e.printStackTrace (); } finalmente {tente {baos.close (); } catch (ioexception e) {e.printStackTrace (); }} retornar nulo; } / ** * Carregar imagem * * @param arquivo * / public static string submitImage (arquivo de arquivo) lança UnsupportEdEncodingException {string filename = urlencoder.encode (file.getName (), "utf-8"); long filesize = file.length (); IsResuffix booleano = true; int altura = 0; int width = 500; String mark = "t"; String mode = "W"; String url = Sign (url) + "& canalno = muying_android" + "& filename =" + fileName + "& filesize =" + fileSize + "& isResuffix =" + isResuffix + "& altura =" + altura + "& width =" + width + "& mark =" System.out.println ("url:" + url); HttpurlConnection Conn = null; OutputStream extream = null; BufferInputStream bin = nulo; tente {bin = new bufferInputStream (new FileInputStream (arquivo)); Conn = (httpurlConnection) novo URL (URL) .OPENCONNECTION (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("post"); Conn.SetDoOutput (true); // Conn.SetFixedLengthStreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application/X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("content-length", file.length () + ""); // Conn.SetRequestProperty ("Range", "Bytes ="+""); // Defina a codificação do caractere de httpurlConnection Conn.setRequestProperty ("aceitar-caracteres", "utf-8"); Outream = Conn.getOutputStream (); byte [] buf = novo byte [1024]; int len = 0; int lEncount = 0; while ((len = bin.read (BUF))! = -1) {Ostream.Write (BUF, 0, Len); // OK Lencount = Lencount + Len; } extream.flush (); int responseCode = conn.getRESPONSecode (); if (Responsecode == 200) {inputStream unstrEam = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; } else {inputStream Instream = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; }} catch (Exceção e) {e.printStackTrace (); } finalmente {try {if (extream! = null) {Outream.close (); }} catch (ioexception e) {e.printStackTrace (); }} retornar nulo; } / ** * Carregar imagem * * @param arquivo * / public static string submitwebImage (arquivo multipartfile) lança UnupportEdEncodingException {string filename = urlencoder.encode (file.getriginalfilename (), "utf-8"); long fileSize = file.getSize (); IsResuffix booleano = true; int altura = 0; int width = 500; String mark = "t"; String mode = "W"; String url = Sign (url) + "& canalno = muying_android" + "& filename =" + fileName + "& filesize =" + fileSize + "& isResuffix =" + isResuffix + "& altura =" + altura + "& width =" + width + "& mark =" System.out.println ("url:" + url); HttpurlConnection Conn = null; OutputStream extream = null; BufferInputStream bin = nulo; tente {bin = new bufferInputStream (file.getInputStream ()); Conn = (httpurlConnection) novo URL (URL) .OPENCONNECTION (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("post"); Conn.SetDoOutput (true); // Conn.SetFixedLengthStreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application/X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("content-comprimento", file.getSize () + ""); // Conn.SetRequestProperty ("Range", "Bytes ="+""); // Defina a codificação do caractere de httpurlConnection Conn.setRequestProperty ("aceitar-caracteres", "utf-8"); Outream = Conn.getOutputStream (); byte [] buf = novo byte [1024]; int len = 0; int lEncount = 0; while ((len = bin.read (BUF))! = -1) {Ostream.Write (BUF, 0, Len); // OK Lencount = Lencount + Len; } extream.flush (); int responseCode = conn.getRESPONSecode (); if (Responsecode == 200) {inputStream unstrEam = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; } else {inputStream Instream = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; }} catch (Exceção e) {e.printStackTrace (); } finalmente {try {if (extream! = null) {Outream.close (); }} catch (ioexception e) {e.printStackTrace (); }} retornar nulo; } / ** * upload de vídeo * * arquivo @param * / public static string submitRadio (arquivo multipart de arquivo) lança a exceção {string url = signoRadio (radiourl); System.out.println ("url:" + url); HttpurlConnection Conn = null; OutputStream extream = null; BufferInputStream bin = nulo; tente {bin = new bufferInputStream (file.getInputStream ()); Conn = (httpurlConnection) novo URL (URL) .OPENCONNECTION (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("post"); Conn.SetDoOutput (true); Conn.SetRequestProperty ("Content-Type", "Application/X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("content-comprimento", file.getSize () + ""); Conn.SetRequestProperty ("Acep-Charset", "UTF-8"); Outream = Conn.getOutputStream (); byte [] buf = novo byte [1024]; int len = 0; int lEncount = 0; while ((len = bin.read (BUF))! = -1) {Ostream.Write (BUF, 0, Len); // OK Lencount = Lencount + Len; } extream.flush (); int responseCode = conn.getRESPONSecode (); if (Responsecode == 200) {inputStream unstrEam = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; } else {inputStream Instream = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; }} catch (Exceção e) {e.printStackTrace (); } finalmente {try {if (extream! = null) {Outream.close (); }} catch (ioexception e) {e.printStackTrace (); }} retornar nulo; } /** * upload retomar instantâneo * * @param fileName * @param Content * @return * @THOWS UnsupportEdEncodingException * /public static string submitfile (nome do arquivo de string, conteúdo de string) lança não suportadoCodingException {////15). nome do arquivo = urlencoder.encode (nome do arquivo, "utf-8"); byte [] contentBytes = content.getBytes (); long fileSize = contentBytes.length; IsResuffix booleano = true; int altura = 0; int width = 500; String mark = "t"; String mode = "W"; String url = Sign (fileurl) + "& canalno = muying_android" + "& filename =" + filename + "& filesize =" + fileSize + "& isResuffix =" + isResuffix + "& altura =" + altura + "& width =" + width + "& mark =" " + Mark +" Modo = " /" Modo = " +" + "& Width =" + Width + "& Mark =" " +" Modo + "& Mode =" +; System.out.println ("url:" + url); HttpurlConnection Conn = null; OutputStream extream = null; BufferInputStream bin = nulo; tente {conn = (httpurlConnection) novo URL (url) .Openconnection (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("post"); Conn.SetDoOutput (true); // Conn.SetFixedLengthStreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application/X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("content-comprimento", content.length () + ""); // Conn.SetRequestProperty ("Range", "Bytes ="+""); // Defina a codificação do caractere de httpurlConnection Conn.setRequestProperty ("aceitar-caracteres", "utf-8"); Outream = Conn.getOutputStream (); overream.Write (contentBytes, 0, contentBytes.length); // ok supertam.flush (); int responseCode = conn.getRESPONSecode (); if (Responsecode == 200) {inputStream unstrEam = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; } else {inputStream Instream = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; }} catch (Exceção e) {e.printStackTrace (); } finalmente {try {if (extream! = null) {Outream.close (); }} catch (ioexception e) {e.printStackTrace (); }} retornar nulo; } / *** upload Anexamento** @return json string* @throws UnsupportEnCodingException* / public static string submitfile (arquivo multipart-arquivo) lança não suportesencodingException {string filename = urlencoder.encode (file.gEGORGINALFILENAME (), " long fileSize = file.getSize (); IsResuffix booleano = true; int altura = 0; int width = 500; String mark = "t"; String mode = "W"; String url = Sign (fileurl) + "& canalno = muying_android" + "& filename =" + filename + "& filesize =" + fileSize + "& isResuffix =" + isResuffix + "& altura =" + altura + "& width =" + width + "& mark =" " + Mark +" Modo = " /" Modo = " +" + "& Width =" + Width + "& Mark =" " +" Modo + "& Mode =" +; System.out.println ("url:" + url); HttpurlConnection Conn = null; OutputStream extream = null; BufferInputStream bin = nulo; tente {bin = new bufferInputStream (file.getInputStream ()); Conn = (httpurlConnection) novo URL (URL) .OPENCONNECTION (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("post"); Conn.SetDoOutput (true); // Conn.SetFixedLengthStreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application/X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("content-comprimento", file.getSize () + ""); // Conn.SetRequestProperty ("Range", "Bytes ="+""); // Defina a codificação do caractere de httpurlConnection Conn.setRequestProperty ("aceitar-caracteres", "utf-8"); Outream = Conn.getOutputStream (); byte [] buf = novo byte [1024]; int len = 0; int lEncount = 0; while ((len = bin.read (BUF))! = -1) {Ostream.Write (BUF, 0, Len); // OK Lencount = Lencount + Len; } int responseCode = Conn.GetRESPONSecode (); if (Responsecode == 200) {inputStream unstrEam = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; } else {inputStream Instream = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; }} catch (Exceção e) {e.printStackTrace (); } finalmente {try {if (extream! = null) {Outream.close (); }} catch (ioexception e) {e.printStackTrace (); }} retornar nulo; } Sign de sequência estática privada (String BaseUrl) lança UnsupportEdEncodingException {Long Currency = System.CurrentTimEmillis (); Timestamp longo = moeda / 1000; String data = "actionName = uploadImage" + "& secretKey = 4b19f08dbf0adb82ce9cc7c207ec1dc9" + "& timestamp =" + timestamp; String Signature = HMAC_SHA1 ("4B19F08DBF0ADB82CE9CC7C207EC1DC9", URLENCODER.ENCODE (Data, "UTF-8")); assinatura = assinatura.Replace ("%3D", "%3D"); assinatura = assinatura.Replace ("%3a", "%3a"); assinatura = assinatura.Replace ("%2f", "%2f"); Retornar Baseurl + Data + "& Signature =" + Signature; } private static string signRadio (string url) lança exceção {long currencybttime = system.currenttimemillis (); String data = "secretKey = f1b79c865c424be46183a2f0a49a0f15" + "& timestamp =" + moeda; System.out.println ("url:" + url + dados); System.out.println ("url =" + urlencoder.encode (URL + dados, "utf-8")); String Signature = hmacsha1util.getSignature (urlencoder.encode (url + dados, "utf-8"), "f1b79c865c424be46183a2f0a49a0f15"); Retorno URL + Data + "& Signature =" + Signature; } string estática privada hmac_sha1 (chave de string, dados de string) {string restring = ""; tente {dados = datas.replace ("%3a", "%3a"); dados = dados.replace ("%2f", "%2f"); dados = dados.replace ("%3d", "%3d"); byte [] data = key.getBytes ("utf-8"); // Construa uma chave com base na matriz de bytes fornecida, e o segundo parâmetro especifica o nome de um algoritmo de chave SecretKeyKey = new SecretKeyspec (Data, "hmacsha1"); // Gere um objeto MAC com o algoritmo Mac especificado Mac = Mac.getInstance ("Hmacsha1"); // Inicialize o objeto Mac com a chave dada Mac.init (secretKey); byte [] text = dados.getBytes ("utf-8"); // complete operação mac byte [] text1 = mac.dofinal (texto); RESTRING = new Base64Encoder (). EncodeBuffer (Text1); RESTRAÇÃO = URLENCODER.ENCODE (RESTRAÇÃO, "UTF-8"); RESTRING = RESTRING.REPLAPE ("%0A", ""); RESTRING = RESTRING.REPLAPE ("%0D", ""); } catch (Exceção e) {e.printStackTrace (); } retornar a restrição; }/** * Faça o upload de imagem cortada * zxiao 2016/09/01 * * @param fileId */public static string submetcutedwebimage (arquivo multipart -arquivo, string fileId, string x, string y, string w, string h) lança não suportescodingExceptExcept {stringId = fileid; String [] CropWidths = new String [] {"50"}; // largura de corte // list <string> list = new List <tring> (); // List <String> List = new ArrayList <String> (5); ArrayList <String> listCropWidths = new ArrayList <String> (); listcropwidths.add ("400"); // string [] CrophEights = new String [] {"50"}; // Crop altura ArrayList <String> listCrophights = new ArrayList <String> (); listcrophights.add ("300"); int colropx = intoger.parseInt (x); // CROUNC x coordenada int colary = Integer.parseInt (y); // Crop y coordenadas // string [] colarfixs = new string [] {"l"}; // Crop imagem Mark Set ArrayList <String> listcropfixs = newRayList <String> () listcropfixs.add ("L"); String fontesffix = "jpg"; // Sufixo base sufixo string fontefix = ""; // logotipo do mapa base/* boolean isResuffix = true; int altura = 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 extream = null; BufferInputStream bin = nulo; tente {bin = new bufferInputStream (file.getInputStream ()); Conn = (httpurlConnection) novo URL (URL) .OPENCONNECTION (); Conn.SetConnectTimeout (15000); Conn.SetRequestMethod ("post"); Conn.SetDoOutput (true); // Conn.SetFixedLengthStreamingMode (file.length ()); Conn.SetRequestProperty ("Content-Type", "Application/X-Www-Form-Urlencoded"); Conn.SetRequestProperty ("content-comprimento", file.getSize () + ""); // Conn.SetRequestProperty ("Range", "Bytes ="+""); // Defina a codificação do caractere de httpurlConnection Conn.setRequestProperty ("aceitar-caracteres", "utf-8"); Outream = Conn.getOutputStream (); byte [] buf = novo byte [1024]; int len = 0; int lEncount = 0; while ((len = bin.read (BUF))! = -1) {Ostream.Write (BUF, 0, Len); // OK Lencount = Lencount + Len; } int responseCode = Conn.GetRESPONSecode (); if (Responsecode == 200) {inputStream unstrEam = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; } else {inputStream Instream = Conn.getInputStream (); byte [] data1 = readaSbyTearr (Instream); String json = new String (Data1); Instruam.close (); retornar JSON; }} catch (Exceção e) {e.printStackTrace (); } finalmente {try {if (extream! = null) {Outream.close (); }} catch (ioexception e) {e.printStackTrace (); }} retornar nulo; }/** A imagem precisa ser salva localmente após o upload e corte * zxiao 2016/09/01 * @param, * @param x * @param y * @param w * @param h * @return * @throws ioexception */public static String submitcropImage (arquivo multipartFILE, Integer x, yoxcept pasta = System.getProperty ("java.io.tmpdir"); Arquivo tempdir = novo arquivo (pasta); // Se a pasta não existir, crie if (! Tempdir .exists () &&! Tempdir .isdir ()) {// system.out.println ("// não existe"); tempdir .mkdir (); } // Arquivo temporário compactado string srcpath = pasta+"scaletemp.jpg"; // Obtenha o sufixo do arquivo/*file uPLOPFILE = novo arquivo (srcpath); InputStream inputStream = file.getInputStream (); FileInputStream fs = (FileInputStream) inputStream; String srcimg = urlencoder.encode (file.getoriginalfilename (), "utf-8"); Sufixo de string = srcimg.substring (srcimg.lastIndexOf (".")+1);*/// corte a imagem Cutimgutils o = new Cutimgutils (x, y, w, h); O.SetSRCPath (SRCPath); o.SetSubPath (pasta+"uptemp.jpg"); Arquivo tempfile = o.cut ("jpg"); String s = submitImage (tempfile); retorno s; }/** * Obtenha a largura da imagem carregada * zxiao 2016/09/09 * arquivo @param * @return */public static int getImgwidth (arquivo multipart -arquivo) lança ioexception {inputStream is = null; BufferImage src = null; int ret = -1; tente {is = file.getInputStream (); src = javax.imageio.imageio.read (IS); ret = src.getwidth (nulo); // obtenha a largura da imagem de origem is.close (); } catch (Exceção e) {e.printStackTrace (); } retornar ret; }/** * Obtenha a imagem carregada alta * zxiao 2016/09/09 * arquivo @param * @return */public static int getImghEight (arquivo multipart -arquivo) {inputStream is = null; BufferImage src = null; int ret = -1; tente {is = file.getInputStream (); src = javax.imageio.imageio.read (IS); ret = src.getheight (nulo); // obtenha a altura da imagem de origem is.close (); } catch (Exceção e) {e.printStackTrace (); } retornar ret; } /*** imagem de escala (escala por altura e largura)* @param Arquivo Objeto do arquivo* @param Resultado Endereço da imagem* @param A altura da altura* @param largura de largura da escala* @param bb é necessário preencher quando a escala estiver incorreta: true é um preenchimento; Falso não está preenchendo; */ public Static Void Scale (arquivo multipart -arquivo, resultado da string, altura int, largura int, booleana bb) {try {double ratio = 0,0; // scaling/*CommonsmultipartFile cf = (CommonsmultipartFile) arquivo; DiskFileItem fi = (DiskFileItem) cf.getFileItem (); Arquivo f = fi.getStorelocation ();*/// arquivo f = novo arquivo (srcImageFile); InputStream inputStream = file.getInputStream (); BufferImage bi = imageio.read (inputStream); Item da imagem = bi.getScaledInstance (largura, altura, bi.scale_smooth); // Calcule a escala if ((bi.getHeight ()> altura) || (bi.getwidth ()> width)) {if (bi.getHeight ()> bi.getwidth ()) {ratio = (novo inteiro (altura). } else {ratio = (novo inteiro (largura)). DoubleValue () / bi.getWidth (); } AffineTransformOp op = new AffineTransformOp (afineTransform .getScaleInstance (razão, razão), nulo); item = op.filter (bi, nulo); } if (bb) {// preencheu bufferImage imagem = new bufferImage (largura, altura, bufferImage.type_int_rgb); Graphics2d g = image.creategraphics (); g.setColor (color.white); G.FillRect (0, 0, largura, altura); if (width == item.getwidth (null)) g.Drawimage (itemp, 0, (altura - item.getHeight (null)) / 2, item.getWidth (null), item.getHeight (nulo), cor.white, null); else G.Drawimage (Itemp, (Width - Item.getWidth (NULL)) / 2, 0, Item.getWidth (NULL), Item.getHeight (null), cor.white, nulo); G.Dispose (); item = imagem; } Imageio.write ((bufferImage) item, "jpg", novo arquivo (resultado)); } catch (ioexception e) {e.printStackTrace (); }} public static void main (string [] args) {try {/* arquivo file = novo arquivo ("e: // bole // doc // interface de serviço documento // interface de serviço bole Descrição v1.0.docx"); System.out.println ("file =" + arquivo); String json = submitfile (arquivo); System.out.println ("json =" + json);*/} catch (Exceção e) {e.printStackTrace (); }}} Ferramentas de corte de imagem
pacote com.shengya.service.utils; importar javax.Imageio.Imageio; importar javax.imageio.imagereadparam; importar javax.imageio.imagereader; import javax.Imageio.Stream.imageInputream; java.io.fileInputStream; importar java.io.ioException; importar java.util.iterator;/*** Criado pelo administrador em 2016/9/1. */public class Cutimgutils {// === O nome do caminho da imagem de origem, como: c: /1.jpg private string srcpath; // === o nome do caminho do armazenamento da imagem do clipe. Por exemplo: c: /2.jpg Substituta privada; public void setSrcPath (String srcPath) {this.srcPath = srcPath; } public void setSubPath (String subpath) {this.subPath = subpath; } // === Ponto de fatia x coordenar privado int x; private int y; // === LIMPANTE DE PONTO DE FLIFT Int Largura; altura privada int; public cutimgutils () {} public cutimgutils (int x, int y, int width, int altura) {if (x <0) {x = 0; } else {this.x = x; } if (y <0) {y = 0; } else {this.y = y; } this.width = width; this.Height = altura; } /** * * Corte a imagem e salve a nova imagem após o corte. */ public File Cut () lança IoException {FileInputStream is = null; ImageInputStream iis = null; tente {// Leia os arquivos da imagem is = new FileInputStream (srcpath); /** * * Retorna o iterador que contém todos os imagens de imagem registrados atualmente, que afirmam poder decodificar o formato especificado. Parâmetros: formatName - contém o nome informal do formato. * * (como "jpeg" ou "tiff"), etc. */ iterator <MageRereader> it = imageio .getImageReaderBerFormatName ("jpg"); ImageReader Reader = it.Next (); // obtenha o fluxo de imagem iis = imageio.createImageInputStream (IS); /** * * <p> * iis: leia a fonte. Verdadeiro: Pesquise apenas a adiante * </p> *. Marque -o como 'Pesquisar apenas adiante'. * * Essa configuração significa que as imagens incluídas na fonte de entrada serão leituras apenas em ordem, o que pode permitir que o leitor * * evite o cache das partes de entrada que contêm dados associados às imagens de leitura anterior. */ reader.setInput (iis, true); /** * * <p> * classe que descreve como decodificar fluxos * <p> *. Usado para especificar como converter uma imagem ou conjunto de imagens de um fluxo no contexto de uma estrutura Java Image E/O * * quando a entrada. O plug -in para um formato de imagem específico * * * Uma instância do ImageReadParam será retornado do método getDefaultreadparam da implementação do ImageReader. */ ImageReadParam param = leitor.getDefaultreadParam (); /** * * Área de corte de imagem. O retângulo especifica uma área no espaço de coordenadas, que pode ser definido pela coordenada (x, y), largura e altura do vértice superior esquerdo do objeto retângulo **. */ Retângulo ret = novo retângulo (x, y, largura, altura); // Forneça um bufferImage para usá -lo como destino para decodificar dados de pixels. param.SetSourCeregion (Rect); /** * Use o ImageReadParam fornecido para ler o objeto especificado pela indexação do ImageIndex e retorne * * como um bufferImage completo. */ BufferErDImage bi = leitor.read (0, param); // salvar nova imagem imageio.write (bi, "jpg", novo arquivo (subpath)); Arquivo de arquivo = novo arquivo ("subpath"); arquivo de retorno; } finalmente {if (is! = null) is.close (); if (iis! = null) iis.close (); }} public File Cut (String Suffix) lança IoException {FileInputStream is = null; ImageInputStream iis = null; tente {// leia o arquivo de imagem é = new FileInputStream (srcpath); // is = inputStream; /** * Retorna o iterador que contém todos os imagens de imagem registrados atualmente * * alegando poder decodificar o formato especificado. Parâmetros: formatName - contém o nome informal do formato. * * (como "jpeg" ou "tiff"), etc. * iterator <MageReader> it = imageio.getImageReaderBerFormatName ("jpg"); */ String sufixName = null; if (sufix.equals ("gif")) {sufixname = "gif"; } else if (sufix.equals ("png")) {suffixname = "png"; } else {suffixName = "jpg"; } Iterator <MageReadeRer> it = imageio .getImageReadesByFormatName (sufixName); ImageReader Reader = it.Next (); // obtenha o fluxo de imagem iis = imageio.createImageInputStream (IS); /** * * <p> * iis: leia a fonte. Verdadeiro: Pesquise apenas a adiante * </p> *. Marque -o como 'Pesquisar apenas adiante'. * * Essa configuração significa que as imagens incluídas na fonte de entrada serão leituras apenas em ordem, o que pode permitir que o leitor * * evite o cache das partes de entrada que contêm dados associados às imagens de leitura anterior. */ reader.setInput (iis, true); /** * * <p> * classe que descreve como decodificar fluxos * <p> *. Usado para especificar como converter uma imagem ou conjunto de imagens de um fluxo no contexto de uma estrutura Java Image E/O * * quando a entrada. O plug -in para um formato de imagem específico * * * Uma instância do ImageReadParam será retornado do método getDefaultreadparam da implementação do ImageReader. */ 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/.
The above is all the content of this article. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.