html
<# - Téléchargez la page de test Avatar à l'aide du plug-in ImareAsElect ->
Enfin téléchargé ce plugin pour apprendre la référence
<link rel = "Stylesheet" type = "text / css" href = "$ {fronTres} /ImGareasel/css/imareasel-animated.css" /> <link rel = "Stylesheet" type = "text / csss" href = "$ {frontres} /ImGareasel/css type = "text / javascript" src = "$ {frontres} /imareasel/jquery-1.4.2.min.js"> </ script> <script type = "text / javascript" src = "$ {FronTres} /ImgareSelect/jQuery.ImgareSelect.pack.js"> </imareselect/jquery.ImgareSelect.pack.js "> </imareselect src = "$ {fronTres} /ImGareSelect/ajaxfileupload.js"> </ script> <script> function addFile (obj) {//document.getElementByid('img').src = path; $ .ajaxfileupload ({url: '$ {huluurl} / formateur / upload / ajaxupload', // L'adresse de la demande côté serveur utilisé pour le fichier téléchargement sécurisé: false, // si un protocole de sécurité est requis Succès: Fonction (Données) {// Le serveur répond avec succès à la fonction de traitement var InfoArray = EVAL ("+ data +") "); Le serveur a échoué, veuillez réessayer plus tard! '); } Fonction Preview (IMG, SELECTION) {if (! SELECTION.Width ||! Selection.Height) return; // Preview var Scalex = 100 / Selection.Width; var scaley = 100 / sélection.height; // var imgx = document.getElementById ("photo"). style.width; var imgx = parseInt ($ ("# photo"). css ("width"). Split ("px") [0]); var imgy = parseInt ($ ("# photo"). css ("height"). Split ("px") [0]); console.debug (imgx + "====" + imgy); $ ('# aperçu img'). css ({width: math.round (scalex * imgx), hauteur: math.round (scaley * imgy), marginleft: -math.round (scalex * selection.x1), margintop: -math.round (Scaley * Selection.y1)}); $ ('# x1'). Val (sélection.x1); $ ('# y1'). Val (sélection.y1); $ ('# x2'). Val (sélection.x2); $ ('# y2'). Val (sélection.y2); $ ('# w'). Val (sélection.Width); $ ('# h'). Val (sélection.Height); // Données backend $ ('# x1S'). Val (sélection.x1); $ ('# y1s'). Val (sélection.y1); $ ('# x2S'). Val (sélection.x2); $ ('# y2s'). Val (sélection.y2); $ ('# imgx'). Val (parseInt (imgx)); // largeur d'origine largeur $ ('# imgy'). Val (parseInt (imgy)); // Hauteur d'origine} $ (fonction (sélection) {var imgx = $ ("# photo"). Css ("width"). Split ("px") [0]; var imgy = $ ("# photo"). CSS ("Height"). Split ("PX") [0]; var ares = 0; console.debug (IMGX + "===" + imgy); if (imgx> imgy) {ares = imgy;} else {ares = imgx;} var ias = $ ('# photo'). Zone de sélection IAS.SetOptions ({Show: True}); 100 / ares; var scaley = 100 / ares; $ ('# aperçu img'). $ ('# x1s'). Val (0); $ ('# y1s'). </cript> <div style = "margin-top: 20px;"> <div> <div> <div> <div> <h4 style = "font-weight: 600; float: Left"> upload the Photo </h4> </v> <div> <div style = "margin-top: 15px"> <v> <v> <div style = "Float: Left"> <div role = "Button" Pisse caché; fond-couleur: # 8dc21f; couleur: #ffffff; "> <span> + ajouter une photo </span> <entrée id =" photofile "type =" file "name =" photofile "onchange =" addfile (this); " Style = "Height: 34px; Position: Absolute; droite: 0px; en haut: 0px; marge: 0px; padding: 0px; curseur: pointeur; opacité: 0;"> </v> </div> <span style = "float: gauche; margin-left: 15px; couleur: # 88888"> <ul> <li> suggèrez vos photos Png, et gif, la taille ne dépasse pas 5m </li> </ul> </span> </div> </div> <div> <div> <img src = "/ images / $ {(Trainer.photo)!" "}" Id = "img"> </ div> </div> </div> </v> <formulaire Action Action " = "$ {Huluurl} / Trainer / upload / uploadPhotoTest" Method = "Post" EncType = "multipart / form-data"> <input type = "text" id = "x1s" name = "x1s" value = "-" /> <input type = "text" id = "y1s" name = "y1s" value = "-" /> <fant type = "id =" name = "va "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 "> re-upload </ Button> </ Div> <v> <Button Type =" soumi "ID =" Baocun "> Enregistrer </ Button> </ Div> </ Div> </ Form> </ Div> </ Div> </ Div> </div> </div> </div> </ div> <div id = "root"> <div id = "main"> <div> <div> <div style = "float: Left; Largeur: 50%; "> <p> Cliquez et faites glisser sur l'image pour sélectionner une zone. </p> <div> <div> <div style =" line-height: 300px; Texte-aligne: Centre; débordement: caché; Z-Index: 1001; Largeur: 300px; hauteur: 300px; Position: relative; Gauche: 50%; en haut: 50%; marge-gauche: -150px; marge: -150px; "> <img id =" photo "src =" / images / $ {(Trainer.photo)! ""} "style =" Max-Height: 300px; max-width: 300px; "/> </div> </div> </div> </div> </div> <div style =" float: Left; Largeur: 50%; "> <p style =" Font-Size: Font-Weight: Bold; Padding-Left: 0.1em; "> Sélection Prévisualiment </p> <div> <div id =" Preview "> <img src =" / images / $ {Trainer.photo!} "/> </div> </div> <Ball> <Thead> <tr> <th Colspan =" 2 "style =" Font-Size: 110%; Police-poids: Bold; Texte-aligne: gauche; padding-left: 0.1em; "> coordonnées </th> <th Colspan =" 2 "style =" font-size: 110%; Police-poids: Bold; Texte-aligne: gauche; padding-left: 0.1em; "> dimensions </th> </tr> </ thead> <tbody> <tr> <td> <b> x <sub> 1 </ sub>: </b> </td> <td> <entrée =" text "id =" x1 "value =" - "/ td> </ td> <td> <b> width: </b> </ td> <td> <b> width: </b> type = "text" value = "-" id = "w" /> </ td> </tr> <tr> <td> <b> y <b> 1 </b>: </b> </td> <td> <entrée Type = "Text" ID = "Y1" Value = "-" /> </ td> <td> <b> HEEPT: </b> </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> <sub> 2 </ subs: </tr> <td> <b> y <sub> 2 </ sub>: </b> </td> <td> <input type = "text" id = "y2" value = "-" /> </td> <td> </v> </v> </v> </v>Java
// Affichage de l'image nécessite un chemin virtuel (tomcat) sur le serveur server.xml < @RequestMapping (value = "touploadphoto", méthode = requestMethod.get) public ModelandView touploadTest () {ModelandView mav = LeftMenu ("/ Trainer / upload / uploadPhoto"); // entraîneur d'entraîneur = null; essayez {long userId = frontshiroutil.getUserId (); if (null! = userId) {Trainer = TrainerRepo.FindOne (userId); TrainerDBSVC.UpDatelastLoginTime (UserId); }} catch (exception e) {e.printStackTrace (); } mav.addObject ("entraîneur", entraîneur); retourner mav; } // Refresh local téléchargement image @RequestMapping ("/ ajaxupload") public @ResponseBody AjaxResult ajaxupload (MultipartHTTPServletRequest request) {Trainer Trainer = new Trainer (); // Obtenez la première image (Obtenez le fichier téléchargé en fonction du nom de la réception) Fichier multipartFile = request.getFile ("PhotoFile"); if (file.getSize ()! = 0) {// Obtenez le nom du fichier: String filename = file.getoriginalFileName (); String TimeType = null; if (null! = filename &&! filename.equals ("")) {String imgType = filename.substring (filename.lasteLexof (".")); // Obtenez la chaîne de chemin ctxpath = "e: / rudongimage / photo /"; // Créer un fichier de fichier dirpath = nouveau fichier (ctxpath); if (! dirpath.exists ()) {dirpath.mkDirs (); } // Prenez le temps de la date du nom du fichier Date = new Date (); SimpledateFormat sdformat = new SimpledateFormat ("yyyymmddhhmms"); // chaîne 24h / 24 lgtime = sdformat.format (date); TimeType = lgtime + imgType; File uploadFile = nouveau fichier (ctxpath + timepey); try {fileCopyUtils.copy (file.getBytes (), uploadFile); } catch (ioException e) {e.printStackTrace (); }} String headphotopath = "Photo /" + TimeType; Trainer.Setphoto (écouteur); } essayez {// interroger le formateur en fonction de l'utilisateur Long Userid = frontshiroutil.getUserId (); if (null! = userId) {Trainer.SetUserId (userId); // Mette à jour le formateur Avatar Trainerdbsvc.UpDateTrainerPhoto (entraîneur); }} catch (exception e) {e.printStackTrace (); } return ajaxResult.CreateSuccess (entraîneur); // <span style = "font-Family: Arial, Helvetica, Sans-Serif;"> ajaxResult peut être modifié </span>} / ** * Intercept Area Téléchargez le test d'image * * @return * / @RequestMapping (Value = "uploadPhototeSt", Method = requestMethod.Post) Public ModelView uploadPhotoTest (multiparThTTSTPSerSerflect, Public ModelView uploadPhoToTEST (MultiaStHtTtsServid.Post) ModelViewView UploadPhoToTEST (MultiaRTHTTTSTServise, demande publique) @RequestParam ("x1s") entier x1, @RequestParam ("y1s") entier y1, @RequestParam ("x2s") entier x2, @RequestParam ("y2s") entier y2, @RequestParam ("IMGX") Imgwidth, @requestParam ("IMGX") Imgwidth, @requestParam ("IMGX") Imgwidth, @requestParam ("IMGX") Imgwidth, @requestParam ("IMGX") Imgwidth, @RequestParam ("IMGX") IMGWIDTHT {ModelAndView Mav = LeftMenu ("redirection: / Trainer / upload / touploadphoto"); Entraîneur entraîneur = null; essayez {// interroge le formateur en fonction de l'utilisateur Long UserId = frontshiroutil.getUserId (); if (null! = userId) {Trainer = TrainerRepo.FindOne (userId); }} catch (exception e) {e.printStackTrace (); } Fichier uploadFile = new File ("e: / rudongimage /" + trash.getphoto ()); InputStream est = null; BufferedImage src = null; int w = -1; int h = -1; try {is = new FileInputStream (uploadFile); src = javax.imageio.imageio.read (is); w = src.getWidth (null); // Obtenez la largeur d'image source h = src.GetHeight (null); // obtient la hauteur du graphique source est.close (); } catch (exception e) {e.printStackTrace (); } Entier l = 0; // utilise les petits bords comme base (taille d'image d'origine) if (w <h) {l = w; } else {l = h; } // Utilisez les petits bords comme base (taille miniature) entier l2 = 0; if (imgwidth <imgheight) {l2 = imgwidth; } else {l2 = imgheight; } Entier x = (x1 * l) / l2; // point de départ x entier y = (y1 * l) / l2; // point de départ y entier xs = (x2 * l) / l2; // point de fin x position diagonale diagonale imageutil ImageUtil = new ImageUtil (); // Renvoie la chaîne de nom de fichier interceptée photoname = ""; imageUtil.cutimage (uploadfile, "e: / rudongimage / photo /", x, y, xs - x, ys - y); String Headphotopath = "Photo /" + Photoname; Trainer.Setphoto (écouteur); // Mette à jour l'avatar TrainerDBSVC.UpDateTrainerPhoto (entraîneur); retourner mav; }Outils
import java.awt.color; import java.awt.graphics; import java.awt.image; import java.awt.rectangle; Importer java.awt.image.bufferedImage; Importer java.io.file; import java.io.fileInputStream; import java.io.filenotfoundException; Importer java.io.ioException; import java.io.inputStream; import java.io.outputStream; import java.util.arrays; Importer java.util.iterator; import javax.imageio.imageio; Importer javax.imageio.imageReadParam; import javax.imageio.imageReader; Importer javax.imageio.stream.imageInputStream; import org.slf4j.logger; import org.slf4j.loggerfactory; / ** * Image Interceptor Tool Class * / public class ImageUtil {private logger log = loggerfactory.getLogger (getClass ()); chaîne statique privée default_thumb_prevfix = "thumb_"; chaîne statique privée default_cut_prevfix = "Cut_"; Private Static Boolean Default_Force = false; / ** * <p> Titre: Cutimage </p> * <p> Description: Intercepter les images locales basées sur l'image d'origine et la taille du crop </p> * @param srcimg Image source * @Param Sortie Image Structive Stream * @param recueillir les coordonnées et la taille de la pièce doit être interceptée * / public Void Cuttimage (fichier srcimg, sortie if (srcimg.exists ()) {java.io.fileInputStream fis = null; ImageInputStream iis = null; try {fis = new FileInputStream (srcimg); // ImageIo prend en charge les types d'images: [BMP, BMP, JPG, JPG, WBMP, JPEG, PNG, PNG, JPEG, WBMP, GIF, GIF] Types de chaînes = Arrays.ToString (imageo.getReaderFormatNames ()). Remplace ("]", "); Chaîne suffixe = null; // obtient le suffixe de l'image if (srcimg.getName (). Indexof (".")> -1) {suffix = srcimg.getName (). Substring (srcimg.getName (). LastIndexof (".") + 1); } // Le type et le suffixe de l'image sont tous en minuscules, puis déterminez si le suffixe est légal si (suffixe == null || types.tolowercase (). Indexof (suffix.tolowercase () + ",") <0) {log.info ("désolé, le suffixe de l'image est illégal. L'image standard est {}." + Types); retour ; } // Convertir FileInputStream en imageInputStream iis = imageo.CreateImageInputStream (fis); // Obtenez l'imageReader de ce type en fonction du type d'image ImageReader Reader = imageo.getImageRedersBySuffix (suffixe) .next (); Reader.SetInput (iis, true); ImageReadParam param = reader.getDefaulTreadParam (); Param.SetSourceRegion (REct); BufferedImage Bi = Reader.read (0, param); Imageo.write (bi, suffixe, sortie); } catch (filenotFoundException e) {e.printStackTrace (); } catch (ioException e) {e.printStackTrace (); } enfin {try {if (fis! = null) fis.close (); if (iis! = null) iis.close (); if (output! = null) output.close (); } catch (ioException e) {e.printStackTrace (); }}}} else {log.info ("L'image src n'existe pas."); }} public void CutImage (fichier srcimg, sortie de sortie, int x, int y, width int, int height) {cutimage (srcimg, output, new java.awt.rectangle (x, y, largeur, hauteur)); } public void CutImage (fichier srcimg, string détimgpath, java.awt.rectangle rect) {file détimg = new file (DetimgPath); if (destimg.exists ()) {String p = detimg.getPath (); essayez {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 ("L'image dest n'existe pas."); }} else log.info ("Le dossier de l'image dest n'existe pas."); } public void cutimage (fichier srcimg, string détimg, int x, int y, int width, int hauteur) {cutimage (srcimg, détimg, new java.awt.rectangle (x, y, largeur, hauteur)); } public void CutImage (String srcimg, String Destimg, int x, int y, int width, int height) {cutimage (nouveau fichier (srcimg), détimg, new java.awt.rectangle (x, y, width, height)); } / ** * <p> Titre: ThumbnailImage </p> * <p> Description: Générez des miniatures basées sur le chemin d'image </p> * @param ImagePath Image Path Image * @param W Wimbnail Width * @param H Thumbnail Height * @param Précédent Générer le préfixe du pouce et la hauteur * @Param force 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 types = arrays.tostring (imageo.getReaderFormatNames ()). Remplacer ("]", ","); Chaîne suffixe = null; // obtient le suffixe de l'image if (srcimg.getName (). Indexof (".")> -1) {suffix = srcimg.getName (). Substring (srcimg.getName (). LastIndexof (".") + 1); } // Le type et le suffixe de l'image sont tous en minuscules, puis déterminez si le suffixe est légal si (suffixe == null || types.tolowercase (). Indexof (suffix.tolowercase () + ",") <0) {log.info ("désolé, le suffixe de l'image est illégal. L'image standard est {}." + Types); retour ; } log.info ("Taille de l'image cible, largeur: {}, hauteur: {}.", w, h); Image img = imageo.read (srcimg); // Trouvez l'échelle miniature la plus appropriée basée sur l'image d'origine et l'échelle de vignette requise if (! Force) {int width = img.getWidth (null); int hauteur = img.getheight (null); if ((width * 1.0) / w <(height * 1.0) / h) {if (width> w) {h = Integer.parseint (new java.text.decimalformat ("0"). format (hauteur * w / (width * 1.0))); log.info ("Changer la hauteur de l'image, largeur: {}, hauteur: {}.", W, h); }} else {if (height> h) {w = Integer.parseint (new Java.text.decimalformat ("0"). Format (largeur * h / (hauteur * 1.0)); log.info ("modifier la largeur de l'image, largeur: {}, hauteur: {}.", W, h);}}} buffle BufferedImage.Type_int_rint_rgb); System.out.println ("Générer l'image de la Chute if (! srcimg.isdirectory ()) p = srcimg.getparent (); (FilenotfoundException e) {log.info ("L'image dest n'existe pas." + E); }} public void thumbnailimage (String ImagePath, int w, int h, string prevFix, booléen force) {file srcimg = new file (imagePath); Thumbnailimage (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 thumbnailimage (String ImagePath, int w, int h) {thumbnaimage (imagePath, w, h, default_force); } public void readusingImageReader (String src, string dest, int w, int h) lève une exception {// obtenir le lecteur d'image Iterator Readers = ImageIo.getImageRedersByFormatName ("png"); ImageReader Reader = (ImageReader) Readers.Next (); // Obtenez le lecteur d'image Flow InputStream Source = new FileInputStream (SRC); ImageInputStream iis = imageo.CreateImageInputStream (source); Reader.SetInput (iis, true); // Paramètres d'image ImageReadParam param = reader.getDefaulTreadParam (); // 100, 200 est la position de départ en haut à gauche, 300 est la largeur de 300, qui est de 300 à partir de 100, soit 100 ~ 400 horizontalement. De même, la superficie de 200 ~ 350 verticalement prend la hauteur de 150 // rectangle REct = nouveau rectangle (100, 200, 300, 150); // int hh = 0; if (h> 100) hh = (h - 100) / 3; Rectangle rect = nouveau rectangle (0, hh, 227, 100); Param.SetSourceRegion (REct); BufferedImage Bi = Reader.read (0, param); ImageIo.Write (BI, "JPG", nouveau fichier (dest)); } public static void main (String [] args) lève une exception {// 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); }}Configuration XML
<bean id = "multipartresolver" class = "org.springframework.web.multupart.commons.commonsMultipartreSolver"> <! - l'une des propriétés disponibles; La taille maximale du fichier dans les octets <propriété name = "maxuploadsize" value = "9999999999" /> -> </ank>
Connexion du plugin
http://download.csdn.net/download/u014596302/9572377
Il existe des fonctions laides si le style n'est pas ajusté.