Spring (java,js,html) screenshot upload picture instance detailed _java

Source: Internet
Author: User

Html


 

Finally uploaded this plugin for a learning reference

<link rel= "stylesheet" type= "Text/css" href= "${frontres}/imgareaselect/css/imgareaselect-animated.css"/> <link rel= "stylesheet" type= "Text/css" href= "${frontres}/imgareaselect/css/index.css"/> <script type= "text /javascript "src=" ${frontres}/imgareaselect/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 ></script> <script> function AddFile ( 
obj) {//document.getelementbyid (' img '). src = path; $.ajaxfileupload ({url: ' ${huluurl}/trainer/upload/ajaxupload ',//server-side request address Secureuri:false for file uploads,//whether security protocols are required, The general setting is False Fileelementid: ' Photofile ',//File upload domain ID dataType: ' JSON ',//return value type is generally set to JSON success:function (data) {//server successfully rang The function var Infoarray = eval ("+data+") should be processed; 
Packet data resolves to json format var arr = Infoarray.data; 
$ ("#img"). attr ("src", "/images/" +arr.photo); }, Error:funCtion () {//server response failed processing function alert (' Communication with server failed, please try again later! 
'); 
Parent.location.reload (); 
} 
}); 
Function Preview (IMG, selection) {if (!selection.width | | |!selection.height) return; 
Preview var scaleX = 100/selection.width; 
var ScaleY = 100/selection.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); $ (' #preview img '). CSS ({width:Math.round (ScaleX * imgx), Height:Math.round (ScaleY * imgy), MarginLeft:-math.round 
(ScaleX * selection.x1), margintop:-math.round (ScaleY * selection.y1)}); 
$ (' #x1 '). Val (selection.x1); 
$ (' #y1 '). Val (selection.y1); 
$ (' #x2 '). Val (selection.x2); 
$ (' #y2 '). Val (selection.y2); 
$ (' #w '). Val (selection.width); 
$ (' #h '). Val (selection.height); 
Background data $ (' #x1s '). Val (selection.x1); 
$ (' #y1s '). Val (selection.y1); 
$ (' #x2s '). Val (selection.x2); 
$ (' #y2s '). Val (selection.y2); $ (' #imgx '). VAl (parseint (IMGX));//original width $ (' #imgy '). Val (parseint (imgy))//Original height} $ (function (selection) {var imgx = $ ("#ph 
Oto "). 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 '). Imgareaselect ({aspectratio: ' 1:1 ', Handles:true, fadespeed:200, Onselectchange:previe 
W, instance:true}); 
Ias.setselection (0, 0, ares-1, ares-1);//Initialize selection area ias.setoptions ({show:true}); 
Ias.update (); 
$ (". Imgareaselect-outer"). CSS ("cursor", "crosshair"); 
$ (". Imgareaselect-outer"). CSS ("Background-color", "Rgba (255,255,255,0.9)"); 
Preview var scaleX = 100/ares; 
var ScaleY = 100/ares; $ (' #preview img '). CSS ({width:Math.round (ScaleX * imgx), Height:Math.round (ScaleY * imgy), MarginLeft:-math.round 
(ScaleX * 0), margintop:-math.round (ScaleY * 0)}); 
Background data $ (' #x1s '). val (0); 
$ (' #y1s '). val (0); $ (' #x2s '). Val (ares-1); 
$ (' #y2s '). Val (ares-1); 
$ (' #imgx '). Val (IMGX)//original width $ (' #imgy '). Val (imgy); </script> <div class= "container" style= "margin-top:20px;" > <div class= "Row" > <div class= "col-xs-9 pull-right" > <div class= "Media media-heading" > 

Java

Display pictures need to configure a virtual path (tomcat) server.xml <context debug= "0" docbase= "G:\Image" path= "/images" reloadable= "true" on the server side > echo the data [Java] View plain copy on the code to see how the line is derived to my Code/** * Jump to upload Avatar 2 (can intercept picture) * * @return/@RequestMapping (value = "T Ouploadphoto ', method = Requestmethod.get] public Modelandview touploadtest () {Modelandview Mav = Leftmenu ("/trainer/up 
Load/uploadphoto "); 
Trainer Trainer = null; 
try {Long userId = Frontshiroutil.getuserid (); 
if (null!= userId) {trainer = Trainerrepo.findone (userId); 
Trainerdbsvc.updatelastlogintime (USERID); 
} catch (Exception e) {e.printstacktrace (); 
} mav.addobject ("trainer", trainer); 
return MAV; //local Refresh upload picture @RequestMapping ("/ajaxupload") public @ResponseBody Ajaxresult Ajaxupload (Multiparthttpservletrequest re 
Quest) {Trainer Trainer = new Trainer (); 
Get the 1th picture (file uploaded according to the name of the foreground) multipartfile file = Request.getfile ("Photofile"); if (file.getsize ()!= 0) {//get filename: String filename = file.getoriginalfilename (); 
String timetype = null; 
if (null!= filename &&!filename.equals ("")) {String Imgtype = filename.substring (Filename.lastindexof (".")); 
Gets the path String Ctxpath = "e:/rudongimage/photo/"; 
Create file Dirpath = new filename (ctxpath); 
if (!dirpath.exists ()) {dirpath.mkdirs (); 
}//time is the filename date = new Date (); 
SimpleDateFormat Sdformat = new SimpleDateFormat ("YYYYMMDDHHMMSS");//24-hour String Lgtime = Sdformat.format (date); 
TimeType = Lgtime + imgtype; 
File UploadFile = new file (Ctxpath + timetype); 
try {filecopyutils.copy (file.getbytes (), uploadfile); 
catch (IOException e) {e.printstacktrace (); 
} String Headphotopath = "photo/" + timetype; 
Trainer.setphoto (Headphotopath); 
try {//According to UserId query trainer Long userId = Frontshiroutil.getuserid (); 
if (null!= userId) {Trainer.setuserid (userId); 
Updated trainer Head Trainerdbsvc.updatetrainerphoto (trainer); 
} catch (Exception e) {e.printstacktrace (); Return ajaxresult.createsuccess (trainer);//<spanStyle= "Font-family:arial, Helvetica, Sans-serif;"  >ajaxresult can modify </span>}/** * Capture area upload picture Test * * @return/@RequestMapping (value = "Uploadphototest", method = Requestmethod.post public Modelandview uploadphototest (multiparthttpservletrequest request, @RequestParam ("X1s") Integer x1, @RequestParam ("y1s") integer y1, @RequestParam ("x2s") Integer x2, @RequestParam ("y2s") integer y2, @RequestP Aram ("Imgx") integer imgwidth, @RequestParam ("imgy") integer imgheight) {modelandview Mav = Leftmenu ("Redirect:/trainer 
/upload/touploadphoto "); 
Trainer Trainer = null; 
try {//According to UserId query trainer Long userId = Frontshiroutil.getuserid (); 
if (null!= userId) {trainer = Trainerrepo.findone (userId); 
} catch (Exception e) {e.printstacktrace (); 
The file UploadFile = new file ("e:/rudongimage/" + Trainer.getphoto ()); 
InputStream is = 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); Get the source graph width h = src.getheight (null); 
Get the source Figure high is.close (); 
catch (Exception e) {e.printstacktrace (); 
The Integer l = 0; 
Whichever is the small edge (original size) if (W < h) {L = W; 
else {L = h; 
///With small edge (thumbnail size) Integer L2 = 0; 
if (ImgWidth < imgheight) {L2 = ImgWidth; 
else {L2 = ImgHeight;  Integer x = (x1 * L)/l2;//start x integer y = (y1 * l)/l2;//start y integer xs = (x2 * l)/l2;//end x Diagonal position Integer ys 
= (y2 * l)/l2;//end y diagonal position imageutil imageutil = new Imageutil (); 
Returns the truncated filename String photoname = ""; 
Imageutil.cutimage (UploadFile, "e:/rudongimage/photo/", X, Y, xs-x, ys-y); 
String Headphotopath = "photo/" + photoname; 
Trainer.setphoto (Headphotopath); 
Updated trainer Head Trainerdbsvc.updatetrainerphoto (trainer); 
return MAV;  }

Tool Class

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; 
Import Java.util.Arrays; 
Import Java.util.Iterator; 
Import Javax.imageio.ImageIO; 
Import Javax.imageio.ImageReadParam; 
Import Javax.imageio.ImageReader; 
Import Javax.imageio.stream.ImageInputStream; 
Import Org.slf4j.Logger; 
Import Org.slf4j.LoggerFactory; 
/** * Image interception Tool Class * * public class Imageutil {private Logger log = Loggerfactory.getlogger (GetClass ()); 
private static String Default_thumb_prevfix = "Thumb_"; 
private static String Default_cut_prevfix = "Cut_"; 
private static Boolean Default_force = false; /** * <p>Title:cutImage</p> * <p>description: According to the original image and cut size to intercept local picture </p> * @param srcimg source picture * @pa RAM Output Image Stream * @param rECT needs to intercept the coordinates and size of the part * * public void Cutimage (File srcimg, outputstream output, Java.awt.Rectangle rect) {if (srcimg.exists) 
) {Java.io.FileInputStream FIS = null; 
Imageinputstream IIS = NULL; 
try {fis = new FileInputStream (srcimg); ImageIO supported picture types: [BMP, BMP, jpg, jpg, wbmp, JPEG, PNG, PNG, JPEG, wbmp, GIF, GIF] String types = arrays.tostring (imag 
Eio.getreaderformatnames ()). Replace ("]", ","); 
String suffix = null; Gets the picture suffix if (srcimg.getname (). IndexOf (".") >-1) {suffix = srcimg.getname (). substring (Srcimg.getname (). LastIndexOf (".") 
+ 1); }//type and picture suffix all lowercase, and then determine whether the suffix is valid if (suffix = null | | types.tolowercase (). IndexOf (Suffix.tolowercase () + ",") < 0) {Log.info ("Sorry, the image suffix is illegal. 
The standard image suffix is {}. "+ types); 
return; 
//Convert FileInputStream to Imageinputstream IIS = Imageio.createimageinputstream (FIS); 
Gets the type of imagereader imagereader reader = imageio.getimagereadersbysuffix (suffix) based on the picture type. Next (); 
Reader.setinput (iis,true); ImagereadParam Param = Reader.getdefaultreadparam (); 
Param.setsourceregion (rect); 
BufferedImage bi = reader.read (0, param); 
Imageio.write (bi, suffix, output); 
catch (FileNotFoundException e) {e.printstacktrace (); 
catch (IOException e) {e.printstacktrace (); 
Finally {try {if (FIS!= null) fis.close (); 
if (IIS!= null) Iis.close (); 
if (output!= null) output.close (); 
catch (IOException e) {e.printstacktrace (); 
}}else {log.info ("The SRC image is not exist."); } public void Cutimage (File srcimg, outputstream output, int x, int y, int width, int height) {cutimage (srcimg, OUTPU 
T, new Java.awt.Rectangle (x, y, width, height)); 
public void Cutimage (file srcimg, String Destimgpath, Java.awt.Rectangle rect) {file destimg = new File (Destimgpath); 
if (destimg.exists ()) {String p = destimg.getpath (); 
try {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 ("The dest image is not exist."); 
}}else Log.info ("The Dest image folder is not exist."); } public void Cutimage (File srcimg, String destimg, int x, int y, int width, int height) {cutimage (srcimg, destimg, new 
Java.awt.Rectangle (x, y, width, height)); public void Cutimage (string srcimg, string destimg, int x, int y, int width, int height) {cutimage (new File (srcimg), D 
Estimg, New Java.awt.Rectangle (x, y, width, height)); /** * <p>Title:thumbnailImage</p> * <p>description: Generate thumbnails from picture path </p> * @param imagepath original picture Path * @param w thumbnail width * @param h thumbnail Height * @param prevfix the prefix for generating thumbnails * @param force whether to force a thumbnail to be generated according to the height (if False, generate the best scale thumbnail) */PU Blic void Thumbnailimage (File srcimg, outputstream output, int w, int h, String prevfix, Boolean force) {if (srcimg.exists ()) {try {//ImageIO supported picture types: [BMP, BMP, jpg, jpg, wbmp, JPEG, PNG, PNG, JPEG, WBMP, GIF, GIF] String types = arrays.tostring (Imageio.getreaderformatnames ()). Replace ("]", ","); 
String suffix = null; Gets the picture suffix if (srcimg.getname (). IndexOf (".") >-1) {suffix = srcimg.getname (). substring (Srcimg.getname (). LastIndexOf (".") 
+ 1); }//type and picture suffix all lowercase, and then determine whether the suffix is valid if (suffix = null | | types.tolowercase (). IndexOf (Suffix.tolowercase () + ",") < 0) {Log.info ("Sorry, the image suffix is illegal. 
The standard image suffix is {}. "+ types); 
return; 
} log.info ("Target image ' size, width:{}, height:{}.", w,h); 
Image img = imageio.read (srcimg); 
Find the most appropriate thumbnail scale if (!force) {int width = img.getwidth (null) based on the original image and the required thumbnail proportions; 
int height = img.getheight (null); if ((width*1.0)/w < (height*1.0)/h) {if (width > w) {h = integer.parseint (new Java.text.DecimalFormat ("0"). Format (H 
Eight * w/(width*1.0))); 
Log.info ("Change image" s height, width:{}, height:{}. ", w,h); } else {if (height > h) {w = integer.parseint (new Java.text.DecimalFormat ("0"). FOrmat (Width * h/(height*1.0))); 
Log.info ("Change image ' s width, width:{}, height:{}.", w,h); 
}} bufferedimage bi = new BufferedImage (W, H, Bufferedimage.type_int_rgb); 
Graphics g = bi.getgraphics (); 
G.drawimage (IMG, 0, 0, W, h, Color.light_gray, NULL); 
G.dispose (); 
Save the picture in the original directory and prefix imageio.write (bi, suffix, output); 
Output.close (); The catch (IOException e) {System.out.println ("Generate thumbnail image failed.") 
+E); 
}}else{System.out.println ("The SRC image is not exist."); } public void Thumbnailimage (File srcimg, int w, int h, String prevfix, Boolean force) {string p = Srcimg.getabsolute 
Path (); 
try {if (!srcimg.isdirectory ()) p = srcimg.getparent (); 
if (!p.endswith (file.separator)) p = p + file.separator; 
Thumbnailimage (srcimg, New Java.io.FileOutputStream (P + prevfix +srcimg.getname ()), W, H, Prevfix, Force); catch (FileNotFoundException e) {log.info ("The dest image is not exist." 
+E); } public void Thumbnailimage (String imagepath, int w, int h, STring Prevfix, Boolean 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_thu 
Mb_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) throws Exception {//Get Picture Reader iterator readers 
= Imageio.getimagereadersbyformatname ("png"); 
ImageReader reader = (imagereader) readers.next (); 
Get the picture read inflow InputStream Source = new FileInputStream (SRC); 
Imageinputstream IIS = Imageio.createimageinputstream (source); 
Reader.setinput (IIS, True); 
Picture parameter Imagereadparam param = Reader.getdefaultreadparam (); 100,200 is the starting position on the left, 300 is to take the width of 300, that is, starting from 100 to take 300 wide, that is, transverse 100~400, the same as the longitudinal 200~350 of the region on the high//Rectangle rect = new Rectangle (100 
)//int hh = 0; if (H > MB) hh = (h-100) /3; 
Rectangle rect = new Rectangle (0, hh, 227, 100); 
Param.setsourceregion (rect); 
BufferedImage bi = reader.read (0, param); 
Imageio.write (BI, "JPG", new File (dest)); public static void Main (string[] args) throws 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);  } 
}

XML configuration

<bean id= "Multipartresolver"
class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!--One of the properties available maximum file size in bytes 
<property name= "Maxuploadsize" Val Ue= "9999999999"/>
-->
</bean>

Plug-in connection

http://download.csdn.net/download/u014596302/9572377

The style is not a bit ugly features have.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.