1, the overall effect chart:
2. Principle of realization:
(1) using the input onchange events to upload pictures asynchronously to the server
(2) Get the relative address of the uploaded picture, echo back to the IMG tag
(3) The use of Jcrop crop pictures, submitted to the background of the start of the cutting coordinates, width, height
(4) Background cropped pictures and save
3, the use of Plug-ins:
(1) jcrop Picture Cutting plugin
(2) asynchronous upload picture plugin: ajaxfileupload.js
4, to achieve:
(1) JSP key code:
<fieldset> <legend> Avatar upload </legend> <!--show pictures of img--> <!--thumbnail preview--> <div id= "Preview-pane" > <div class= "Preview-container" > </div> </div> <div class= "container" > <!--Open Picture control-- > <span class= "Btn btn-success Fileinput-button "> <i class=" icon- Plus icon-white "></i> <span& gt; Select pictures </span> <input type= "fil E "onchange=" Ajaxfileupload () "Name=" Realpicfile "id=" realpicfile "multiple/> </span> <!-- This practice IE does not support, denied access to . <input id= "realpicfile" value= "Select Picture" Onchange= "Ajaxfileupload ()" type= "file" style= "Display:none;" name= "Realpicfile"/> <a class= "btn btn-success href=" javascript:selectpic (); "> <i class= "Icon-plus icon-white" ></i> Select pictures </a>--> <!--upload and crop pictures--> <a class= "btn btn-success" href= "Javascript:cutpic" (); ><i class= "Icon-picture icon-white" ></i> Save head </a> <!--get the starting coordinates and width of the crop, height to background--> <form. id= " Coords "class=" coords "> <div class=" inline-labels "> <input type=" hidden "size=" 4 "id=" x1 "name=" x 1 "/> <input type=" hidden "size=" 4 "id=" y1 "name=" y1 "/> <input type=" hidden "size=" 4 "id=" X2 "n Ame= "X2"/> <input type= "hidden" size= "4" id= "y2" name= "y2"/> "<input type=" hidden "size=" 4 "id=" "W" name= "W"/> <input type= "hidden" size= "4" id= "H" name= "H"/> </div> </form> < /div> </fieldset>
Control CSS for styles:
. Jcrop-holder #preview-pane {width:156px;
height:156px;
Display:block;
Position:absolute;
/*z-index:2000;*/top:0px;
Right: -200px;
padding:6px;
border:1px Rgba (0,0,0,.4) solid;
Background-color:white;
-webkit-border-radius:6px;
-moz-border-radius:6px;
border-radius:6px;
-webkit-box-shadow:1px 1px 5px 2px rgba (0, 0, 0, 0.2);
-moz-box-shadow:1px 1px 5px 2px rgba (0, 0, 0, 0.2);
box-shadow:1px 1px 5px 2px rgba (0, 0, 0, 0.2); }/* The Javascript code would set the aspect ratio of the crop area based on the size of the thumbnail preview, spe
cified here * * * #preview-pane preview-container {width:156px;
height:156px;
Overflow:hidden;
} #target-pane {width:400px;
height:400px;
}. Fileinput-button {position:relative;
Overflow:hidden;
}. Fileinput-button input {position:absolute;
top:0;
right:0;
margin:0;
opacity:0;
Filter:alpha (opacity=0);
Transform:translate ( -300px, 0) scale (4); Font-size:23px
direction:ltr;
Cursor:pointer; }
Note Fileinput-button This style, I am unfamiliar with CSS, so this code is copied from the Jquery-file-upload plug-in, probably means that the file input to the button, put to transparent, so that can be compatible with IE, Otherwise, if the input is hidden, and the Click event that triggers it, IE does not think it is safe to do so, the report denied access error.
(2), JavaScript key code:
Create variables to hold the API and image size Var jcrop_api, boundx, Boundy, path; /** * Update thumbnail, implementation principle: According to the original text box selection, display to the thumbnail, and the thumbnail is also the original image is magnified, just more than the part of the IMG range is hidden/function Updatepreview (c) {if parseint (C.W) >
0) {$ (' #x1 '). Val (c.x);
$ (' #y1 '). Val (C.Y);
$ (' #x2 '). Val (c.x2);
$ (' #y2 '). Val (c.y2);
$ (' #w '). Val (C.W);
$ (' #h '). Val (c.h);
var rx = XSIZE/C.W;
var ry = ysize/c.h; Accurately calculates the position of the picture $pimg. css ({width:Math.round (RX * boundx) + ' px ', Height:Math.round (ry * boundy) + ' px ', margi
Nleft: ' + math.round (RX * c.x) + ' px ', margintop: '-' + math.round (ry * c.y) + ' px '}; /** * Asynchronously upload picture * @returns {Boolean}/function Ajaxfileupload () {$ ("#loading"). Ajaxstart (function () {$ (this). s
how ();
)//Start uploading the file to display a picture. Ajaxcomplete (function () {$ (this). Hide ();
//File Upload complete hides the picture var file = $ ("#realPicFile"). Val (); if (!/\. ( Gif|jpg|jpeg|png| Jpg| PNG) {$/.test (file)) {Error ("Unsupported picture format.) The picture type must be. jpeg,jpg,png,gif format. ");
return false; } $.ajaxfileupload ({url:Util.getContentPath () + '/user/uploadheaderpictmp.do?inputid=realpicfile ',//server-side requests for file uploads Address secureuri:false,//is generally set to false fileelementid: ' Realpicfile ',//File upload Space id attribute <input type= "file" id= "file" Nam e= "File"/> dataType: ' json ',//return value type is generally set to JSON success:function (data, status)/Server Success Response processing function {//Picture in
Relative address on server, plus random number to prevent not refreshing path = Util.getcontentpath () + Data.path + "?" + math.random ();
$ ("#realPic"). attr ("src", path);
var IMGs = $ (". Jcrop-holder"). FIND ("img");
Originally have pictures, after uploading, all img need to refresh Imgs.each (function (i, v) {$ (this). attr ("src", path);
});
$ (' #preview-pane preview-container img '). attr ("src", path); Chettu style//Grab Some information about the preview pane $preview = $ (' #preview-pane '), $pcnt = $ (' #preview-pane. Pre
View-container '), $pimg = $ (' #preview-pane. Preview-container img '), xsize = $pcnt. Width (), ysize = $pcnt. Height (); Console. log (' init ', [Xsize, Ysize]); $ (' #realPic '). Jcrop ({onchange:updatepreview,//Chettu box Change event Onselect:updatepreview,//Chettu box Select Event Onrelease:clearcoords,//Chettu
box to release the event Bgfade:true, Bgopacity:. 8,///screenshot frame outside the transparency setselect: [10, 10, 100, 100],//default selected area Aspectratio:1//xsize/ysize screenshot Ratio, here I use the ratio of 1:1, which is cut out as a square}, function () {//Use the APIs to get the real image
size var bounds = this.getbounds ();
Boundx = Bounds[0];
Boundy = bounds[1];
Store the API in the JCROP_API variable jcrop_api = this;
Move the preview to the Jcrop container for CSS positioning $preview. appendto (Jcrop_api.ui.holder);
});
}, Error:function (data, status, E)//server response failure processing function {error (E);
}
});
return false;
function _getshowwidth (str) {return _getvalue (str, "width");}
function _getshowheight (str) {return _getvalue (str, "height");} function _getvalue (str, key) {var str = str.replace (/\:|\;|\s/g, ''). toLowerCase ();
var pos = str.indexof (key);
if (pos >= 0) {//intercept var TMP = str.substring (pos, str.length);
var px = tmp.indexof ("px");
if (px > 0) {var width = tmp.substring (key.length, px);
return width;
return 0;
return 0; /** * Crop picture/function Cutpic () {//Initialize data var x1 = $ (' #x1 '). val () = ""?
0: $ (' #x1 '). Val (); var y1 = $ (' #y1 '). val () = ""?
0: $ (' #y1 '). Val ();
var x2 = $ (' #x2 '). Val ();
var y2 = $ (' #y2 '). Val (); var w = $ (' #w '). val () = ""?
$ (' #w '). Val (); var h= $ (' #h '). val () = ""?
$ (' #h '). Val ();
var srcfile = $ ("#realPic"). attr ("src"); if (Srcfile = = "" | |!
Srcfile) {Error ("no picture selected.");
Return
var Showdiv = $ (". Jcrop-holder > Jcrop-tracker"); From the compression of the image of the div to obtain the compressed display width and height, used to the background with the proportion of cutting//width:404px; height:304px; Position:absolute; Top: -2px; Left: -2px; z-index:290;
Cursor:crosshair;
var style = Showdiv.attr ("style");
The width of the original picture page displayvar showwidth = _getshowwidth (style);
The original picture page displays the height of var showheight = _getshowheight (style);
Console.log (Showwidth + "" + showheight);
The SRC address of the original map, remove the random number srcfile = srcfile.substring (0, Srcfile.indexof ("?") that prevents the refresh from being removed. $.ajax ({type: "Post", DataType: "JSON", Url:Util.getContentPath () + "/user/uploadheaderpic.do", D ATA: {srcimagefile:srcfile, x:x1, Y:y1, Destwidth:w, Destheight:h, srcshow Width:showwidth, Srcshowheight:showheight,}, Success:function (data) {var okcallback = Functi
On () {this.top.window.location = Util.getcontentpath () + "/user/pcmodiinfoinit.do";
};
var msg = eval (data);
if (msg && msg.msg) if (Msg.code = = 1) Alert (msg.msg, okcallback);
else Error (msg.msg, okcallback);
else {Error ("Upload failed, please try again later.", Okcallback);
Return
}, Error:function () {error ("Upload failed, please try again later.");
} }); function Clearcoords () {$ (' #coords input '). Val (');
(3) SPRINGMVC code:
@RequestMapping ("uploadheaderpictmp") @ResponseBody public string Uploadheaderpic (string inputID,
Multiparthttpservletrequest request) {try {multipartfile realpicfile = Request.getfile (inputID);
InputStream in = Realpicfile.getinputstream ();
String path = Request.getsession (). Getservletcontext (). Getrealpath ("/");
Path = TMP;
User Loginuser = Systemutil.getloginuser (Request.getsession ());
String fileName = loginuser.getname () + "." + filenameutils.getextension (Realpicfile.getoriginalfilename ());
File F = new file (path + "/" + fileName);
Fileutils.copyinputstreamtofile (in, f);
Return "{\" path\ ": \" "+ TMP +"/"+ FileName +" \ "}";
catch (Exception e) {log.error ("Upload header picture error:", e);
return null; @RequestMapping ("Uploadheaderpic") @ResponseBody public generalmessage cutimage (String srcimagefile, int x, int y, I
NT Destwidth, int destheight, int srcshowwidth, int srcshowheight, httpservletrequest request) {try { String path = Request.getsession (). Getservletcontext (). Getrealpath ("/");
Image img;
ImageFilter Cropfilter;
String srcfilename = Filenameutils.getname (srcimagefile);
Read source image file Srcfile = new file (path + TMP + "/" + srcfilename);
BufferedImage bi = imageio.read (srcfile); Front page display is not the original size, but after a certain compression, so you can not use the width of the original image to crop, you need to use the front display of the picture wide-high int srcwidth = Bi.getwidth (); SOURCE graph width int srcheight = Bi.getheight ();
SOURCE Graph Height if (srcshowwidth = = 0) Srcshowwidth = srcwidth;
if (Srcshowheight = = 0) Srcshowheight = srcheight; if (srcshowwidth >= destwidth && srcshowheight >= destheight) {Image image = Bi.getscaledinstance (srcsh Owwidth, Srcshowheight, Image.scale_default)//Get scaled picture size Cropfilter = new CropImageFilter (x, Y, Destwidth, Destheig
HT);
img = Toolkit.getdefaulttoolkit (). CreateImage (New FilteredImageSource (Image.getsource (), cropfilter)); BufferedImage tag = new BufferedImage (Destwidth, Destheight, Bufferedimage.type_INT_RGB);
Graphics g = tag.getgraphics (); G.drawimage (IMG, 0, 0, NULL);
Draw the captured figure g.dispose ();
String ext = filenameutils.getextension (srcimagefile);
Path + header_pic;
User Loginuser = Systemutil.getloginuser (Request.getsession ());
String fileName = loginuser.getname () + "." + ext;
File Destimagefile = new file (path + "/" + fileName);
Output for file Imageio.write (tag, ext, destimagefile);
Loginuser.setpicpath (systemconst.system_context_path_value + header_pic + "/" + fileName);
Userservice.update (Loginuser);
Delete the original temporary file Srcfile.delete ();
Generalmessage msg = new Generalmessage ();
Msg.setcode (generalmessage.success); Msg.setmsg ("uploaded successfully.")
");
return msg;
} catch (Exception e) {e.printstacktrace ();
return null; }