html
<#-Subir la página de prueba de avatar usando el complemento Imgareaselect->
Finalmente subí este complemento para aprender referencia
<link rel = "stylesheet" type = "text/css" href = "$ {frontres} /imgareasel/css/imgareasel-animated.css"/> <link rel = "stylesheet" type = "text/css" href = "$ {frontres} /imgarsel/css/index.csss type = "text/javaScript" src = "$ {frontres} /imgareasel/jquery-1.4.2.min.js"> </script> <script type = "text/javascript" src = "$ {frontres} /imgarElect/jquery.imgareAselect.pack.js"> </script> <script type = "text/" "text/" javaScript "" src = "$ {frontres} /imgareaselect/AJAXFILEUPLOAD.JS"> </script> <script> function addFile (obj) {//document.getElementByid('Img').src = ruta; $ .AJAXFILEUPLOAD ({URL: '$ {HULUURL}/TRABAJO/upload/AJAXUPLOAD', // La dirección de solicitud del lado del servidor se usa para la carga de archivo Secureuri: false, // Si se requiere un protocolo de seguridad, generalmente se establece en False FalleEmementId: 'PhotOfile', // ID de la ID de Domain de archivo. A JSON Success: Function (Data) {// El servidor responde con éxito a la función de procesamiento var infoArray = eval ("("+data+")"); El servidor falló, intente nuevamente más tarde! '); } función previa (img, selección) {if (! Selection.Width ||! Selection.Height) return; // Preview var escalax = 100 /selection.width; var scaley = 100 / selection.Height; // var imgx = document.getElementById ("foto"). style.width; var imgx = parseInt ($ ("#foto"). CSS ("ancho"). Split ("Px") [0]); var imgy = parseInt ($ ("#foto"). CSS ("altura"). Split ("Px") [0]); console.debug (imgx+"===="+imgy); $ ('#Preview img'). CSS ({Width: Math.round (escalax * imgx), altura: math.round (scaley * imgy), marginleft: -math.round (scalex * selection.x1), margintop: -math.round (scaley * selección.y1)}); $ ('#x1'). Val (selección.x1); $ ('#y1'). Val (Selection.y1); $ ('#x2'). Val (selección.x2); $ ('#y2'). Val (Selection.y2); $ ('#W'). Val (Selection.Width); $ ('#H'). Val (Selection.Height); // datos de backend $ ('#x1s'). Val (selección.x1); $ ('#y1s'). Val (Selection.y1); $ ('#x2S'). Val (selección.x2); $ ('#y2s'). Val (Selection.y2); $ ('#imgx'). val (parseint (imgx)); // Ancho de ancho original $ ('#imgy'). Val (parseint (imgy)); // altura original} $ (function (selection) {var imgx = $ ("#foto"). Css ("ancho"). Split ("px") [0]; var imgy = $ ("#foto"). Css ("altura"). Split ("px") [0]; var ares = 0; console.debug (imgx+"====" if (imgx> imgy) {ares = imgy;} else {ares = imgx; área iAs.setOptions ({show: true}); ares; $ ('#y1s'). Val (0); </script> <div style = "margin-top: 20px;"> <div> <div> <div> <div> <h4 style = "font-weight: 600; float: izquierda"> cargar la foto </h4> </div> <div> <dryle = "margin-top: 15px"> <div> <div> <div> <divsy style = "float: izquierda"> <div> style ";" style ";" Overflow: Hidden; Background-Color: #8DC21F; color: #ffffff; "> <span>+Agregar una foto </span> <input id =" Photofile "type =" file "name =" Photofile "onChange =" addFile (this); " estilo = "altura: 34px; posición: absoluto; derecha: 0px; top: 0px; margen: 0px; relleno: 0px; cursor: pointer; opacidad: 0;"> </div> </div> <span style = "float: izquierda; margen-margen: 15px; color: #888888"> <ul> <li> sugiere sus fotos </li> solo) PNG, y GIF, el tamaño no excede 5M </li> </ul> </span> </div> </div> <div> <div> <div> <img src = "/images/$ {(entrenador.photo)!" "}" Id = "img"> </div> </div> </div> </div> <portion action -<port action = "$ {huluurl}/entrenador/upload/uploadphotest" método = "post" enctype = "multipart/form-data"> <input type = "text" id = "x1s" name = "x1s" valor = "-"/> <input type = "text" id = "y1s" name = "y1s" value = "-"/> <<put type de entrada = "text" name "" x2 "nombre" name "name" name "name" name "name" nam " "x2s" value="-" /> <input type="text" id="y2s" name = "y2s" value="-" /> <input type="text" id="imgx" name = "imgx" value="-" /> <input type="text" id="imgy" name = "imgy" value="-" /> <div style="margin-top: 15px; margin-left: 80px"> <Div> <div> <button type = "button" id = "chongxinshangchuan"> reupload </botón> </div> <div> <button type tipo = "enviar" id = "baocun"> guardar </boton> </div> </borm> </form> </div> </div> </div div> <div id = "root"> <div id = "main"> <div> <div> <div style = "float: izquierda; Ancho: 50%; "> <p> Haga clic y arrastre la imagen para seleccionar un área. </p> <div> <div> <div style =" Line-HEight: 300px; Text-Align: Center; desbordamiento: oculto; Index Z: 1001; Ancho: 300px; Altura: 300px; Posición: relativo; Izquierda: 50%; arriba: 50%; margen -izquierda: -150px; margen -top: -150px; "> <img id =" Photo "src ="/images/$ {(entrenador.photo)! ""} "style =" max-height: 300px; max-width: 300px; "/> </div> </div> </div> </div> </div> <divsy style =" float: izquierda; Ancho: 50%; "> <p style =" Font-Size: Font-Weight: Bold; Padding-Left: 0.1em; "> Vista previa de selección </p> <div> <div id =" vista previa "> <img src ="/images/$ {Trainer.photo!} "/> </div> </div> <table> <thead> <tr> <th colspan =" 2 "style =" Font-tize: 110%; Font-Weight: Bold; text-align: izquierda; Padre-izquierda: 0.1em; "> Coordenadas </th> <th colspan =" 2 "style =" Font-size: 110%; Font-Weight: Bold; text-align: izquierda; almohadilla: 0.1em; "> type = "text" value = "-" id = "w"/> </td> </tr> <tr> <tr> <td> <b> y <sub> 1 </sub>: </b> </td> <td> <input type = "text" id = "y1" value = "-"/> </td> <td> <b> altura: </b> </b> </td> <td> 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 <sub> 2 </sub>: </b> </td> <td> <input type = "text" id = "y2" value = "-"/> </td> <td> </td> <td> </td> </bbody> </bable> </div> </iv> </iv> </div> <Viv>Java
// Mostrar la imagen requiere una ruta virtual (TomCat) en el servidor Server.xml <context debug = "0" docbase = "g:/image" path = "/images" reloadable = "true"/> echo los datos [java] ver fragmentos de código de copia simple en el código derivado de mis fragmentos de código/** * iba a la carga de datos (puede capturar imágenes) * @ @ @ @ @ @ @ @ @ @ @@returno/ @@return = "touploadphoto", método = requestmethod.get) public modelandView touploadTest () {modelandView mav = LeftMenu ("/Trainer/upload/uploadPhoto"); // entrenador entrenador = nulo; intente {long userId = frontshiroutil.getUserId (); if (null! = userId) {Trainer = TrainerRepo.Findone (UserId); TrainerDBSVC.UpDatelastLogIntime (UserId); }} catch (Exception e) {E.PrintStackTrace (); } mav.addoBject ("entrenador", entrenador); regresar mav; } // Imagen de carga de actualización local @RequestMapping ("/Ajaxupload") public @ResponseBody AjaxResult Ajaxupload (MultipthttpServletRequest solicitud) {Trainer Trainer = new Trainer (); // Obtenga la primera imagen (obtenga el archivo cargado de acuerdo con el nombre de la recepción) el archivo multipartfile = request.getFile ("Photofile"); if (file.getSize ()! = 0) {// Obtenga el nombre del archivo: string filename = file.getOriginalFileName (); String timeType = null; if (null! = filename &&! FileName.equals ("")) {string imgType = filename.substring (filename.lastIndexof (".")); // Obtener la cadena de ruta ctxpath = "e:/rudonMage/photo/"; // crear archivo de archivo dirpath = nuevo archivo (ctxpath); if (! dirpath.exists ()) {dirpath.mkdirs (); } // tomar tiempo como fecha de nombre del archivo fecha = nueva fecha (); SimpleDateFormat sdFormat = new SimpleDateFormat ("yyyymmddhhmmss"); // string 24-horas lgtime = sdformat.format (fecha); TIMETYPE = LGTIME + IMGTYPE; Archivo uploadFile = nuevo archivo (ctxpath + timeType); intente {fileCopyUtils.copy (file.getBytes (), uploadFile); } catch (ioException e) {E.PrintStackTrace (); }} String Headphotopath = "Photo/" + Timetype; entrenador.setphoto (Headphotopath); } try {// consulta el entrenador basado en UserId Long userId = frontshiroutil.getUserId (); if (null! = userId) {Trainer.setUserID (userId); // Actualizar el entrenador Avatar TrainerDBSVC.UpdatetRainerphoto (entrenador); }} catch (Exception e) {E.PrintStackTrace (); } return aJaxResult.CreateSuccess (entrenador); // <span style = "font-family: Arial, Helvetica, sans-serif;"> ajaxResult se puede modificar </span>}/** * Intercept Area Subiendo la prueba de imagen * * @return */@RequestMapping (value = "uploadphotest", método = requestmethod.post) public ModelandView UploadPhotest (múltiple (múltiple @RequestParam ("x1s") Integer X1, @RequestParam ("Y1S") Integer Y1, @RequestParam ("X2S") Integer X2, @RequestParam ("Y2S") Integer Y2, @RequestParam ("IMGX") INTERGER IMGWIDTH, @RequestParam ("IMGY" IMGY "IMGER") IMGER) {ModelAndView mav = LeftMenu ("Redirect:/Trainer/upload/Touploadphoto"); Entrenador entrenador = nulo; Pruebe {// Consulta el entrenador basado en UserID Long UserId = frontshiroutil.getUserId (); if (null! = userId) {Trainer = TrainerRepo.Findone (UserId); }} catch (Exception e) {E.PrintStackTrace (); } Archivo uploadFile = nuevo archivo ("e:/rudonMage/" + entrenador.getPhoto ()); InputStream es = nulo; BufferedImage src = null; int w = -1; int h = -1; prueba {IS = new FileInputStream (uploadFile); src = javax.imageio.imageio.read (is); w = src.getWidth (nulo); // Obtener el ancho de la imagen de origen H = src.getheight (nulo); // Obtener la altura del gráfico de origen IS.Close (); } catch (Exception e) {E.PrintStackTrace (); } Entero l = 0; // Use bordes pequeños como base (tamaño de imagen original) if (w <h) {l = w; } else {l = h; } // usa bordes pequeños como base (tamaño de miniatura) entero l2 = 0; if (imgwidth <imgheight) {l2 = imgwidth; } else {l2 = imgheight; } Entero x = (x1 * l)/ l2; // Punto de partida x Integer y = (y1 * l)/ l2; // Punto de partida Y entero xs = (x2 * l)/ l2; // Punto final x Posición diagonal Integer YS = (Y2 * L)/ L2; // Punto final Y Posición diagonal Imagenutil = New Imageutil (); // devuelve el nombre de archivo interceptado String Photoname = ""; imageUtil.cutImage (uploadfile, "e:/rudonMage/photo/", x, y, xs - x, ys - y); String Headphotopath = "Photo/" + Photoname; entrenador.setphoto (Headphotopath); // Actualizar el avatar del entrenador TrainerDBSVC.UpdatetRainerphoto (entrenador); regresar mav; }Herramientas
import java.awt.color; import java.awt.graphics; import java.awt.image; import java.awt.rectangle; import java.awt.image.bufferedImage; import java.io.file; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.ioException; import java.io.inputstream; import java.io.outputstream; importar java.util.arrays; import java.util.iterator; import javax.imageio.imageio; import javax.imageio.imageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.imageInputStream; importar org.slf4j.logger; importar org.slf4j.loggerFactory; / *** Clase de herramienta de interceptor de imágenes*/ public class ImiceUtil {private logger log = loggerFactory.getLogger (getClass ()); cadena estática privada default_thumb_prevfix = "thumb_"; cadena estática privada default_cut_prevfix = "Cut_"; Private static boolean default_force = false; /*** <p> Título: CutImage </p>* <p> Descripción: Interceptar imágenes locales basadas en la imagen original y el tamaño de la cosecha </p>* @param srcimg Imagen de origen* @param salida de salida de salida flujo* @param rect rect the coordinate y tamaño de la parte debe ser interceptado*/public Cutimage (file srcimg, salida de salida, salida, java.awt.awt. {{{{{{{ if (srcimg.exists ()) {java.io.fileInputStream fis = null; ImageInputStream iis = null; intente {fis = new FileInputStream (srcIMG); // ImageIO admite tipos de imágenes: [BMP, BMP, JPG, JPG, WBMP, JPEG, PNG, PNG, JPEG, WBMP, GIF, GIF] Tipos de cadenas = Arrays.ToString (imageIO.getReaderFormAtNames ()). Reemplace ("]", "); String sufijo = nulo; // Obtenga el sufijo de imagen if (srcimg.getName (). IndexOf (".")> -1) {sufix = srcimg.getName (). Substring (srcimg.getName (). LastIndexOf (".") + 1); } // El tipo y el sufijo de imagen son todos en minúsculas y luego determinan si el sufijo es legal si (sufix == null || types.tolowercase (). IndexOf (suffix.tolowercase () + ",") <0) {log.info ("lo siento, el sufijo de imagen es ilegal. El sufijo de imagen estándar es {}." + Tipos); devolver ; } // Convertir fileInputStream a ImageInputStream iis = imageIO.CreateImageInputStream (FIS); // Obtenga ImageReader de este tipo de acuerdo con el tipo de imagen ImageReader Reader = ImageIO.GetImageReadersBySuffix (sufijo) .next (); lector.setInput (IIS, verdadero); ImagereadParam param = lector.getDefaultreadParam (); param.setSourCeregion (RECT); BufferedImage bi = lector.read (0, param); Imageio.write (bi, sufijo, salida); } catch (FileNotFoundException e) {E.PrintStackTrace (); } catch (ioException e) {E.PrintStackTrace (); } finalmente {try {if (fis! = null) fis.close (); if (iis! = null) iis.close (); if (salida! = null) output.close (); } catch (ioException e) {E.PrintStackTrace (); }}}} else {log.info ("La imagen src no existe."); }} public void cutImage (archivo srcimg, salida de salida de salida, int x, int y, int width, int altura) {cutImage (srcImg, salida, nueva java.awt.rectangle (x, y, ancho, altura)); } public void cutImage (archivo srcimg, string Destimgpath, java.awt.rectangle rect) {file destimg = new File (DestimgPath); if (destimg.exists ()) {String p = Destimg.getPath (); intente {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 + "_" + nuevo java.util.date (). gettime () + "_" + srcimg.getName ()), rect); } Catch (FileNotFoundException e) {log.info ("La imagen Dest no es existe"); }} else log.info ("La carpeta de imagen Dest no existe"); } public void cutImage (archivo srcimg, string destimg, int x, int y, int width, int altura) {cutIMage (srcimg, destimg, new java.awt.rectangle (x, y, ancho, altura)); } public void cutImage (String srcimg, string Destimg, int x, int y, int width, int altura) {cutIMage (nuevo archivo (srcimg), desestimg, nuevo java.awt.rectangle (x, y, ancho, altura)); }/*** <p> Título: ThiGnailImage </p>* <p> Descripción: Genere las miniaturas basadas en la ruta de la imagen </p>* @param ImagePath ruta de imagen original* @param w width* @param h HOYGNAIL altura* @Param Generar el prefix de la thumbnail* @Param Force si la fuerza de la fuerza a la fuerza de la fuerza a la fuerza de la fuerza a la luz de la fuerza de la fuerza de la fuerza y la altura de la altura de la que se genere y se genere la altura de la fuerza de la fuerza. false, 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 tipos = arrays.toString (imageIO.getReaderFormatNames ()). Reemplazar ("]", ","); String sufijo = nulo; // Obtenga el sufijo de imagen if (srcimg.getName (). IndexOf (".")> -1) {sufix = srcimg.getName (). Substring (srcimg.getName (). LastIndexOf (".") + 1); } // El tipo y el sufijo de imagen son todos en minúsculas y luego determinan si el sufijo es legal si (sufix == null || types.tolowercase (). IndexOf (suffix.tolowercase () + ",") <0) {log.info ("lo siento, el sufijo de imagen es ilegal. El sufijo de imagen estándar es {}." + Tipos); devolver ; } log.info ("tamaño de imagen de destino, ancho: {}, altura: {}.", w, h); Imagen img = ImageIO.Read (srcimg); // Encuentre la escala de miniatura más adecuada basada en la imagen original y la escala de miniatura requerida if (! Force) {int width = img.getWidth (null); int altura = img.getheight (nulo); if ((ancho*1.0)/w <(altura*1.0)/h) {if (width> w) {h = integer.parseInt (nuevo java.text.decimalformat ("0"). format (altura*w/(ancho*1.0))); log.info ("Cambiar la altura de la imagen, ancho: {}, altura: {}.", w, h); }} else {if (altura> h) {w = integer.ParseInt (new java.text.DecimalFormat ("0"). Format (width * h/(Height * 1.0)); log.info ("Cambiar el ancho de la imagen, ancho: {}, altura: {}.", W, h);}}} biñera bix. BufferedImage.type_int_rgb); System.out.println ("Generar la imagen de la miniatura fallida."+E); if (! srcimg.isDirectory ()) p = srcimg.getParent (); (FileNotFoundException e) {log.info ("La imagen Dest no existe."+E); }} public void ThiGnailImage (String ImagePath, int W, int h, String Prevfix, Boolean Force) {file srcimg = new File (ImagePath); ThiGnailImage (Srcimg, W, H, Prevfix, Force); } public void ThumbnailImage (String ImagePath, int W, int h, boolean force) {ThumbnailImage (ImagePath, W, H, default_thumb_prevfix, default_force); } public void ThiGnailImage (String ImagePath, int w, int h) {ThumbnailImage (ImagePath, W, H, default_force); } public void ReadusingImageReader (String Src, String Dest, int W, int h) lanza la excepción {// Obtener el lector de imágenes iterator Readers = ImageIO.GetImageReadersByFormatName ("Png"); Imagereader Reader = (ImageReader) Readers.next (); // Obtenga la fuente de entrada del lector de imágenes Source = new FileInputStream (SRC); ImageInputStream IIS = imageIO.CreateEmageInputStream (fuente); lector.setInput (IIS, verdadero); // Parámetros de imagen ImageReadParam Param = Reader.getDefaultreadParam (); // 100, 200 es la posición inicial en la esquina superior izquierda, 300 es el ancho de 300, que es 300 de 100, que es 100 ~ 400 horizontalmente. Del mismo modo, el área de 200 ~ 350 toma verticalmente la altura de 150 // rectángulo rect = nuevo rectángulo (100, 200, 300, 150); // int hh = 0; if (h> 100) hh = (h - 100) / 3; Rectángulo rect = nuevo rectángulo (0, HH, 227, 100); param.setSourCeregion (RECT); BufferedImage bi = lector.read (0, param); Imageio.write (bi, "jpg", nuevo archivo (des)); } public static void main (string [] args) lanza la excepción {// nueva imageUtil (). ThumbnailImage ("imgs/tulips.jpg", 150, 100); // new imageUtil (). cutImage ("imgs/tulips.jpg", "imgs", 250, 70, 300, 400); // new imageUtil (). ReadusingImageReader ("E: //rudontimege/photo/2016030302090226.png", "e: //rudongimage/photo/2.png", 227, 163); }}Configuración XML
<bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.commonsmultipARTresolver"> <!- una de las propiedades disponibles; El tamaño máximo del archivo en bytes <propiedad name = "maxUploadSize" value = "9999999999"/>-> </bean>
Conexión de complemento
http://download.csdn.net/download/u014596302/9572377
Hay algunas funciones feas si el estilo no se ajusta.