html
<#-Carregue a página de teste de avatar usando o plug-in iMgareasElect->
Finalmente enviou este plugin para aprender a referência
<link rel = "Stylesheet" type = "text/css" href = "$ {Frontres} /imgareasel/css/imgareasel-animated.css"/> <link rel = "stylesheet" type = "text/css" href = "$ {FrontRres} type="text/javascript" src="${frontRes}/imgareasel/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="${frontRes}/imgareaselect/jquery.imgareaselect.pack.js"></script> <script type="text/javascript" src = "$ {FRontres} /imgareaselect/ajaxfileupload.js"> </cript> <cript> função addfile (obj) {//document.getElementById('Img'iM.Src = Path; $ .ajaxfileUpload ({url: '$ {huluurl}/treinador/upload/ajaxupload', // O endereço de solicitação do servidor-side usado para upload de arquivo Secureuri: False, // se um protocolo de segurança é necessário, geralmente é definido para o FalseLementIdyMement: 'fotófile', // idéias de segurança, geralmente é definido para o FileAnMementiEnMemeMype: 'fotofile', // para JSON Sucesso: Função (Data) {// O servidor responde com sucesso à função de processamento var infoArray = Eval ("("+dados+")"); alerta ('comunicação com o servidor falhou, tente novamente mais tarde!'); } Função visualização (img, seleção) {if (! Seleção.width ||! Seleção.Height) retornar; // visualizar var scalex = 100 /seleção.width; var scaley = 100 / seleção.Height; // var iMgx = document.getElementById ("foto"). style.width; var iMgx = parseint ($ ("#foto"). css ("largura"). split ("px") [0]); var imgy = parseint ($ ("#foto"). css ("altura"). split ("px") [0]); console.debug (imgx+"===="+imgy); $ ('#visualize img'). css ({width: math.round (scalex * imgx), altura: math.ound (scaley * imgy), marginleft: -math.ound (scalex * seleção.x1), margintop: -math.Round (scaley * selection.y1)}); $ ('#x1'). val (seleção.x1); $ ('#y1'). val (seleção.y1); $ ('#x2'). val (seleção.x2); $ ('#y2'). val (seleção.y2); $ ('#w'). Val (seleção.width); $ ('#h'). Val (seleção.Height); // dados de back -end $ ('#x1s'). val (seleção.x1); $ ('#y1s'). val (seleção.y1); $ ('#x2s'). val (seleção.x2); $ ('#y2s'). val (seleção.y2); $ ('#imgx'). Val (Parseint (IMGX)); // largura original de largura $ ('#imgy'). Val (parseint (imgy)); // altura original} $ (função (seleção) {var iMgx = $ ("#foto"). Css ("largura"). Split ("px") [0]; var iMgy = $ ("#foto"). Css ("altura"). Split ("px") [0]; if (imgx> imgy) {arres = imgy; Área de seleção ias.setOptions (Mostrar: True}); Ares; $ ('Y1S'). Val (0); </script> <div style = "margin-top: 20px;"> <div> <div> <div> <div> <h4 style = "font-weight: 600; float: esquerda"> carregue a foto </h4> </button </div> <div style = "margin-top: 15px"> <d4> <> stylesty = " Hidden; Background-Color: #8dc21f; cor: #ffffff; "> <pan>+Adicione uma foto </span> <entrada id =" fotofile "type =" file "name =" photofile "onchange =" addfile (this); " style="height:34px;position: absolute; right: 0px; top: 0px; margin: 0px; padding: 0px; cursor: pointer; opacity: 0;"> </div> </div> <span style="float: left; margin-left: 15px; color: #888888"> <ul> <li>Suggest your photos</li> <li>Only support JPG, Png e gif, o tamanho não excede 5m </li> </ul> </span> </div> </div> <div> <div> <img src = "/imagens/$ {(treinador.photo)!" "}" Id = "img"> </div> </div> </div) = "$ {huluurl}/treinador/upload/uploadphototest" method = "post" rtype = "multipart/form-data"> <input type = "text" id = "x1s" name = "x1s" yourning = "-"/> <input = "text ="/"y1s" name "=" y1s "y) id = "x2s" name = "x2s" value = "-" /> <input type = "text" id = "y2s" name = "y2s" value = "-" /> <input type = "text" id = "iMgx" name = "imgx" "-" " /> <input type =" text "<bx" name "name =" imgx ""-"" /> <input = "text" <di-gx "(" imgx "=") ") 15px; </div> </div> </div> </div> <div id = "root"> <div id = "main"> <div> <div> <div style = "float: esquerda; largura: 50%; "> <p> Clique e arraste a imagem para selecionar uma área. Alinhamento de texto: centro; estouro: oculto; Index z: 1001; Largura: 300px; Altura: 300px; Posição: relativa; Esquerda: 50%; TOP: 50%; margem -esquerda: -150px; Margin -top: -150px; "> <img id =" photo "src ="/imagens/$ {(treinador.photo)! ""} "style =" max-height: 300px; max-width: 300px; "/> </div> </div> </div> </div> <div estilo") largura: 50%; "> <p style =" font-size: font-weight: BOLD; preenchimento de preenchimento: 0.1em; "> visualização de seleção </p> <div> <div id =" visualize "> <img src ="/imagens/$ {treiner.photo!} "/> </div> </div> <table> <thead> <tr> <th colspan =" 2 "style =" font-size: 110; Peso da fonte: negrito; Alinhamento de texto: esquerda; Potding-left: 0.1em; "> coordenadas </th> <th colspan =" 2 "style =" font-size: 110%; Peso da fonte: negrito; Alinhamento de texto: esquerda; preenchimento-left: 0.1em; "> dimensões </th> </tr> </sead> <tbody> <tr> <td> <b> x <uns> 1 </suge>: </b> </td> <td> <td type =" text "iD =" x1 "="-"/> </td> <td> type = "text" value = "-" id = "w"/> </td> </tr> <tr> <td> <b> y <subt> 1 </suge>: </b> </td> <td> <input type = "text" id = "y1" = "-"/</td> <tg> <btlening "" = "y1" = "-"/</td> <t> <b "" id="h" value="-" /></td> </tr> <tr> <td><b>X<sub>2</sub>:</b></td> <td><input type="text" id="x2" value="-" /></td> <td></td> <td><b>Y<sub>2</sub>:</b></td> <td> </td> </tr> <td> <b> y <uns> 2 </suge>: </b> </td> <td> <input type = "text" id = "y2" value = "-"/> </td> <td> </td> <td> </td> </tum> </thant> </thant> <td> <td> </td> <td> </td> </tum>Java
// mostra a imagem requer um caminho virtual (tomcat) no servidor server.xml <context debug = "0" docbase = "g:/image" path = "/imagens" recarregável = "true"/> eco * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '/imagens é uma das imagens' e imagens 'relusable = 0 ”. = "touploadphoto", método = requestmethod.get) public ModelAndView Touploadtest () {ModelAndView MAV = leftmenu ("/treinador/upload/uploadphoto"); // treinador treinador = nulo; tente {long userId = ftershiroutil.getUserID (); if (null! = userID) {treinador = treinadorrepo.findone (userID); treinadordbsvc.updatelastLogIntime (UserID); }} catch (Exceção e) {e.printStackTrace (); } mav.addobject ("treinador", treinador); retornar mav; } // Local Refresh Upload Image @ReQuestMapping ("/Ajaxupload") public @ResponseBody AjaxResult Ajaxupload (multiparthttpServletRequest Solicy) {treinador treinador = novo treinador (); // Obtenha a primeira imagem (obtenha o arquivo enviado de acordo com o nome da recepção) FILETFILE MultipartFile = request.getFile ("Photofile"); if (file.getSize ()! = 0) {// obtenha o nome do arquivo: string filename = file.getoriginalfilename (); String timeType = null; if (null! = FileName &&! FileName.equals ("" ") {String imgtype = filename.substring (filename.lastindexOf (". ")); // obtenha o caminho string ctxpath = "e:/rudongimage/foto/"; // Criar arquivo Arquivo Dirpath = novo arquivo (CTXPath); if (! Dirpath.Exists ()) {dirpath.mkdirs (); } // reserve um tempo como o nome do arquivo date = new Date (); SimpledateFormat sdformat = new SimpleDateFormat ("yyyymmddhhmmss"); // string 24-hour lgtime = sdformat.format (data); timeType = lgtime + imgtype; FILE UPLOPLEFILE = novo arquivo (CTXPath + TimeType); tente {FileCopyutils.copy (file.getBytes (), uploadfile); } catch (ioexception e) {e.printStackTrace (); }} String headphotopath = "foto/" + timeType; treinador.setphoto (fofetopata); } tente {// consulte o treinador com base no userID long userID = ftershiroutil.getUserId (); if (null! = userID) {treinador.setUserID (userID); // Atualize o treinador Avatar TrainerDBSVC.UPDATETRAINERPHOTO (treinador); }} catch (Exceção e) {e.printStackTrace (); } retornar ajaxResult.createsuccess (treinador); //<span style="font-family: Arial, Helvetica, sans-serif;">AjaxResult can be modified</span> } /** * Intercept area upload image test* * @return */ @RequestMapping(value = "uploadPhotoTest", method = RequestMethod.POST) public ModelAndView uploadPhotoTest(MultipartHttpServletRequest request, @RequestParam ("x1s") inteiro x1, @requestParam ("y1s") inteiro y1, @requestParam ("x2s") inteiro x2, @requestParam ("y2s") Integer y2, @requestParam ("imgx") intereghid) {ModelAndView MAV = LeftMenu ("Redirect:/treinador/upload/touploadphoto"); Treinador treinador = nulo; tente {// consulte o treinador com base no userID long userID = ftshiroutil.getUserId (); if (null! = userID) {treinador = treinadorrepo.findone (userID); }} catch (Exceção e) {e.printStackTrace (); } Arquivo uploadfile = novo arquivo ("e:/rudongimage/" + treinador.getphoto ()); InputStream é = nulo; BufferImage src = null; int w = -1; int h = -1; tente {is = new FileInputStream (uploadFile); src = javax.imageio.imageio.read (IS); w = src.getwidth (nulo); // obtenha a largura da imagem de origem h = src.getheight (null); // obtenha a altura do gráfico de origem is.close (); } catch (Exceção e) {e.printStackTrace (); } Número inteiro l = 0; // Use pequenas bordas como base (tamanho da imagem original) se (w <h) {l = w; } else {l = h; } // Use pequenas arestas como base (tamanho da miniatura) inteiro l2 = 0; if (imgwidth <imgheight) {l2 = imgwidth; } else {l2 = imgheight; } Número inteiro x = (x1 * l)/ l2; // ponto de partida x número inteiro y = (y1 * l)/ l2; // ponto de partida y inteiro xs = (x2 * l)/ l2; // ponto final x posição de diagonal; // retorna o nome do arquivo interceptado string photoname = ""; imageUtil.cutimage (uploadfile, "e:/rudongimage/foto/", x, y, xs - x, ys - y); String headphotopath = "foto/" + fottoname; treinador.setphoto (fofetopata); // Atualize o treinador do treinador TrainerDBSVC.UpDateTrenerphoto (treinador); retornar mav; }Ferramentas
importar java.awt.color; importar java.awt.graphics; importar java.awt.image; importar java.awt.rectangle; importar java.awt.image.bufferiMage; importar java.io.file; importar java.io.fileInputStream; importar java.io.filenotfoundException; importar java.io.ioException; importar java.io.inputStream; importar java.io.OutputStream; importar java.util.arrays; importar java.util.iterator; importar javax.imageio.imageio; importar javax.imageio.imagereadparam; importar javax.imageio.imagereader; importar javax.imageio.stream.imageInputStream; importar org.slf4j.logger; importar org.slf4j.loggerFactory; / *** Classe de ferramenta de interceptores de imagem*/ public class ImageUtil {private logger log = loggerFactory.getLogger (getClass ()); String estática privada default_thumb_prevfix = "Thumb_"; String estática privada default_cut_prevfix = "cut_"; private estático booleano default_force = false; /*** <p> Título: CutImage </p>* <p> Descrição: Interceptar imagens locais com base na imagem original e no tamanho da colheita </p>* @param srcimg imagem de origem* @param saída de imagem fluxo de saída* @param RECT OSTRCINATAS E O TAMANHO DA PARTE precisam ser interceptos*/public void Cutimage (SRCIMG if (srcimg.exists ()) {java.io.fileInputStream fis = null; ImageInputStream iis = null; tente {fis = new FileInputStream (srcimg); // Imageio suporta tipos de imagem: [BMP, BMP, JPG, JPG, WBMP, JPEG, PNG, PNG, JPEG, WBMP, GIF, GIF] TIPOS DE String = Arrays.ToString (imageio.getReReformatNames ()). String sufix = null; // Obtenha o sufixo da imagem if (srcimg.getName (). } // O sufixo do tipo e da imagem são todos minúsculos e, em seguida, determine se o sufixo é legal se (suffix == null || types.TolowerCase (). retornar ; } // Converte FileInputStream em imageInputStream iis = imageio.createImageInputStream (fis); // Obtenha o ImageReader desse tipo de acordo com o tipo de imagem ImageReader Reader = imageio.getImageReaderSbySuffix (sufixo) .Next (); leitor.setInput (iis, true); ImageReadParam param = reader.getDefaultreadParam (); param.SetSourCeregion (Rect); BufferImage bi = leitor.read (0, param); Imageio.write (bi, sufixo, saída); } catch (filenotfoundException e) {e.printStackTrace (); } catch (ioexception e) {e.printStackTrace (); } finalmente {tente {if (fis! = null) fis.close (); if (iis! = null) iis.close (); if (output! = null) output.Close (); } catch (ioexception e) {e.printStackTrace (); }}}} else {log.info ("A imagem SRC não existe."); }} public void CutImage (arquivo srcimg, saída de saída, int x, int y, int width, int altura) {cutimage (srcimg, saída, new java.awt.rectangle (x, y, largura, altura)); } public void CutImage (arquivo srcimg, string destimgpath, java.awt.rectangle ret) {arquivo destimg = new File (destimgPath); if (destimg.exists ()) {string p = destimg.getPath (); tente {if (! Destimg.isdirectory ()) p = destimg.getParent (); if (! p.endswith (file.separator)) p = p + file.separator; CutImage (srcimg, new java.io.fileOutputStream (p + default_cut_prevfix + "_" + new java.util.date (). gettime () + "_" + srcimg.getname ()), rect); } catch (filenotfoundException e) {log.info ("A imagem do dest existe."); }} else Log.info ("A pasta de imagem Dest não existe."); } public void CutImage (arquivo srcimg, string destimg, int x, int y, int width, int alting) {cutimage (srcimg, destimg, new java.awt.rectangle (x, y, largura, altura)); } public void CutImage (string srcimg, string destimg, int x, int y, int width, int alting) {cutimage (novo arquivo (srcimg), destimg, novo java.awt.rectangle (x, y, largura, altura)); }/*** <p> Título: Thumbnailimage </p>* <p> Descrição: Gere miniaturas com base no caminho da imagem </p>* @Param ImagePath Original Image Path* @param w WithMail Lidth* @param hthumbnail alting* @param prevfix Gere o prefixo do Thumbnail* the best scale thumbnail is generated) */ public void thumbnailImage(File srcImg, OutputStream output, int w, int h, String prevfix, boolean force){ if(srcImg.exists()){ try { // ImageIO Supported image types: [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG, JPEG, Wbmp, gif, gif] string types = Arrays.toString (imageio.getReaderFormatNames ()). Substituir ("]", ","); String sufix = null; // Obtenha o sufixo da imagem if (srcimg.getName (). } // O sufixo do tipo e da imagem são todos minúsculos e, em seguida, determine se o sufixo é legal se (suffix == null || types.TolowerCase (). retornar ; } log.info ("Tamanho da imagem de destino, largura: {}, altura: {}.", w, h); Imagem img = imageio.read (srcimg); // Encontre a escala de miniatura mais adequada com base na imagem original e na escala de miniatura necessária if (! Force) {int width = img.getwidth (nulo); int height = img.getheight (nulo); if ((largura*1.0)/w <(altura*1.0)/h) {if (width> w) {h = integer.parseint (novo java.text.decimalformat ("0"). formato (altura*w/(largura*1.0))); log.info ("Alterar a altura da imagem, largura: {}, altura: {}.", w, h); }} else {if (Height> h) {W = Integer.parseInt (novo java.text.DecimalFormat ("0"). BufferImage.type_int_rgb); System.It.println ("Geree a imagem da miniatura."+E); if (! srcimg.isdirectory ()) p = srcimg.getparent (); (FileNotfoundException e) {log.info ("A imagem do dest existe."+E); }} public void ThumbnailImage (String ImagePath, int w, int h, string prevfix, força booleana) {arquivo srcimg = new File (imagepath); Thumbnailimage (srcimg, w, h, prevfix, force); } public void thumbnailimage (String ImagePath, int w, int h, força booleana) {thumbnailimage (imageath, w, h, default_thumb_prevfix, default_force); } public void ThumbnailImage (String ImagePath, int w, int h) {ThumbnailImage (ImagePath, W, H, Default_force); } public void readUsingImageReader (String src, string dest, int w, int h) lança exceção {// Obtenha o Image Reader iteterator Readers = imageio.getImageReRersByFormatName ("png"); ImageReader Reader = (ImageReader) Readers.Next (); // Obtenha a imagem do leitor de imagem InputStream fonte = new FileInputStream (SRC); ImageInputStream iis = imageio.createImageInputStream (fonte); leitor.setInput (iis, true); // parâmetros de imagem imageReadParam param = leitor.getDefaultreadParam (); // 100, 200 é a posição inicial no canto superior esquerdo, 300 é a largura de 300, que é 300 de 100, que é de 100 ~ 400 horizontalmente. Da mesma forma, a área de 200 ~ 350 pega verticalmente a altura de 150 // retângulo Rect = novo retângulo (100, 200, 300, 150); // int hh = 0; if (h> 100) hh = (h - 100) / 3; Retângulo ret = novo retângulo (0, hh, 227, 100); param.SetSourCeregion (Rect); BufferImage bi = leitor.read (0, param); Imageio.write (bi, "jpg", novo arquivo (dest)); } public static void main (string [] args) lança Exceção {// new ImageUtil (). ThumbnailImage ("imgs/tulips.jpg", 150, 100); // new imageUtil (). CutImage ("imgs/tulips.jpg", "imgs", 250, 70, 300, 400); // new imageUtil (). ReadUsingImageReader ("e: //rudongimage/photo/20160302090226.png", "e: //rudongimage/photo/2.png", 227, 163); }}Configuração XML
<bean id = "multipartresolver" class = "org.springframework.web.multipart.commons.commonsmultipartresolver"> <!- uma das propriedades disponíveis; O tamanho máximo do arquivo em bytes <propriedade name = "maxuploadsize" value = "99999999999"/>-> </sien>
Conexão do plug -in
http://download.csdn.net/download/u014596302/9572377
Existem algumas funções feias se o estilo não for ajustado.