Jquery. Jcrop combining Java background to achieve picture cropping upload instance _jquery

Source: Internet
Author: User

This article introduces the avatar cutting upload function, the technology used has JQUERY,SPRINGMVC, the cutting plug-in uses is Jcrop (in the middle encounters many pits, finally crosses).

Picture upload step:

1. User Select picture

2. The picture into the background: the user chooses the picture when the choice is various, but our webpage displays the picture size is limited, therefore we must after the user chooses the picture to add the picture to the backstage to compress, compresses the size which we want, then displays again to the page to be good

3. Crop the picture using the Jcrop cropping tool and preview it in real time

4. Click OK button to cut the parameters used in the background, the background picture to cut, and then scale to the format we need

5. Finally upload the picture path to the front desk for display

The front page code is:

<script src= "Js-jcrop/jquery.min.js" ></script> <script src= "Js-jcrop/jquery". Jcrop.js "></script> <script src=" js/jquery-form.js "></script> <link rel=" stylesheet "href=" .. /css/jquery. Jcrop.css "type=" Text/css "/> <style type=" Text/css ">/* Control Preview Area Size */#preview-pane. Preview-container {Width 
 : 110px; 
 height:110px; 
Overflow:hidden; 
 } #targetDiv {width:400px; 
 height:400px; 
Background-color: #f7fdff; } </style> <dl class= DialogBox d_uploadlogo > <dt class= Dialogheader > <span class= Le "> Avatar upload </span> </dt> <dd class=" Dialogbody "> <dl class=" Bisinesslogo "> & Lt;dt class= "title" > Preview </dt> <dd class= "img" > <div id= "Preview-pane" > <d 
          IV class= "Preview-container" >  
   </div> </div>   </dd> <dd class= "TC" > Size:110*110px</dd> </dl> <dl class= "Bisinessinfo" > <dt class= "btnBox02" > <form id= "fileup" action= "/file/img/upload" method= "POST" enctype= "multipart /form-data "target=" IFM "> <a class=" Btngray "javascript:;" 
            > <span class= "text" id= "format" > select picture </span> <b class= "BgR" ></b> <input type= "File" id= "File_upload" class= "Inputfile" name= "Userphoto"/> "<input type=" Hidd En "id=" w "name=" W "/> <input type=" hidden "id=" H "name=" H "/> <input" type= "id 
      = "X" name= "x"/> <input type= "hidden" id= "y" name= "y"/> </a> </form> </dt> <dd class= "info" > Please select a picture locally to support jpg,png format <span id= "MSG" ></span& 
        Gt <div id= "Targetdiv" >  </div> </dd> </dl> </d d> <input type= "hidden" id= "Filepathinput" value= ""/> <dd class= "Dialogbottom" > <a class= "b Tnblue btn_confirm "href=" javascript:; "onclick=" photosummit (); " ><span class= "text" > OK </span><b class= "BgR" ></b></a> <a class= "Btngray btn_ Cancel "href=" javascript:; "onclick=" Hidedialog (); 
 ><span class= "Text" > Cancel </span><b class= "BgR" ></b></a> </dd> </dl>

1. Choose a picture

 

2. Submit: First of all, you know the file upload time to use the tag is: <input type= "file"/> But sometimes we need to use Ajax to submit files and asynchronous submission, if we are using form forms to submit the word is not asynchronous, so we go back to the page to refresh the page , very inconvenient, but now Ajax can not support the way the file is submitted, this time we used the Jquery-form.js, this file support us to use AJAX to submit the file, the code is:

$ ("#fileUp"). <span style= "color: #ff0000;" >ajaxSubmit</span> ({ 
      type: "POST", 
      URL: "/file/img/upload", 
      dataType: "JSON" 
      , ContentType: "Application/json",  
        success:function (parameter) { 
        $ ("#target2"). attr (' src ', '/upload/' + Parameter.filename); 
        $ ("#filePathInput"). Val ('/upload/' +parameter.filename); 
        if ($ ("#format"). Text () = "re-upload") { 
          Jcrop_api.destroy () 
        } 
        $ ("#format"). Text ("Re-uploading"); 
        Start Jcrop support 
        openjcrop ('/upload/' +parameter.filename); 
      }, 
      error:function (data) {  
        alert (" An error occurred in the AJAX transfer!!! "); 
      }  
     }); 

This will be able to use the Ajax way to submit files to the background, note that this is Ajaxsubmit, this method corresponds to Jquery-form.js, the background code is:

Package com.quanshi.ums.gate.view.rest.controllers; 
Import java.io.IOException; 
Import Javax.servlet.http.HttpServletRequest; 
Import Javax.servlet.http.HttpServletResponse; 
Import javax.servlet.http.HttpSession; 
Import Org.slf4j.Logger; 
Import Org.slf4j.LoggerFactory; 
Import Org.springframework.stereotype.Controller; 
Import org.springframework.web.bind.annotation.RequestMapping; 
Import Org.springframework.web.bind.annotation.RequestMethod; 
Import Org.springframework.web.bind.annotation.RequestParam; 
Import Org.springframework.web.bind.annotation.ResponseBody; 
Import Org.springframework.web.multipart.MultipartFile; 
Import Com.quanshi.ums.gate.persistence.entities.Parameters; 
 Import Com.quanshi.ums.gate.view.rest.ImgEditor; /** * Image upload and modify related class * @author Kunpeng.zhao * */@Controller @RequestMapping (value= "/file") public class Fileeditor 
Controller {<span style= "white-space:pre" > </span>imgeditor imgeditor = new Imgeditor (); <span style= "White-spAce:pre "> </span>public String filepathfinal =" "; <span style= "White-space:pre" > </span>private Logger Logger = Loggerfactory.getlogger ( 
Fileeditorcontroller.class); <span style= "White-space:pre" > </span> @RequestMapping (value= "/img/cutandscale", method= Requestmethod.post) <span style= "White-space:pre" > </span>public @ResponseBody int cutandscaleimg (< Span style= "White-space:pre" > </span> @RequestParam ("w") int W, <span style= "White-space:pre" > &L T;/span> @RequestParam ("h") int h, <span style= "White-space:pre" > </span> @RequestParam ("x") int x, &L T;span style= "White-space:pre" > </span> @RequestParam ("y") int y <span style= "White-space:pre" > & lt;/span>) {<span style= "White-space:pre" > </span>imgeditor.cut (filepathfinal,filepathfinal,x,y,w, 
h); <span style= "White-space:pre" > </span>imgeditor.scale (filepathfinal, filepathfinal, 110,, false); 
<span style= "White-space:pre" > </span>return 1; <span style= "White-space:pre" > </span&gt} <span style= "White-space:pre" > </span> <span Style = "White-space:pre" > </span> @RequestMapping (value= "/img/upload", method=requestmethod.post) public @Respon Sebody Parameters addimage (<span style= "White-space:pre" > </span> @RequestParam ("Userphoto") Multipartfi Le file, <span style= "White-space:pre" > </span>httpservletrequest request, <span style= "White-space :p Re "> </span>httpservletresponse response, <span style=" White-space:pre "> </span>httpsession Session <span style= "White-space:pre" > </span>) {<span style= "White-space:pre" > </span>str  
  ing filePath = ""; <span style= "White-space:pre" > </span>try {<span style= "white-space:pre" > </span>//upload Artwork ; span style= "White-space:pre" > </span>filepath = imgeditor.uploadfile (file, request,session); 
<span style= "White-space:pre" > </span>filepathfinal = FilePath; <span style= "White-space:pre" > </span>//compress the picture to the specified size <span style= "White-space:pre" > &LT;/SPAN&G 
T;imgeditor.zoomimage (filepath,filepath,400,400);      <span style= "White-space:pre" > </span>} catch (IOException e) {<span style= ' white-space:pre ' > 
</span>e.printstacktrace (); 
    <span style= "White-space:pre" > </span> Logger.info ("FilePath:" + FilePath); 
    Parameters parameter = new Parameters (); 
  Parameter.setfilename (Imgeditor.getfilename (file,request,session)); 
  <span style= "White-space:pre" > </span>return parameter; 
 } 
   
   
   
   
}

I'm here to specify that the picture in the foreground shows the size of 400*400, use the picture clipping compression, and so on the tool class is:

Package com.quanshi.ums.gate.view.rest; 
Import Java.awt.Color; 
Import Java.awt.Graphics; 
Import Java.awt.Graphics2D; 
Import Java.awt.Image; 
Import Java.awt.Toolkit; 
Import Java.awt.geom.AffineTransform; 
Import java.awt.image.AffineTransformOp; 
Import Java.awt.image.BufferedImage; 
Import Java.awt.image.CropImageFilter; 
Import Java.awt.image.FilteredImageSource; 
Import Java.awt.image.ImageFilter; 
Import Java.io.File; 
Import java.io.IOException; 
Import Java.text.SimpleDateFormat; 
 
Import Java.util.Date; 
Import Javax.imageio.ImageIO; 
Import Javax.servlet.http.HttpServletRequest; 
 
Import javax.servlet.http.HttpSession; 
Import Org.springframework.security.core.context.SecurityContextHolder; 
 
Import Org.springframework.web.multipart.MultipartFile; public class Imgeditor {/** * change picture size * @param srcfilename source Picture path * @param tagfilename destination Picture path * @param Width Modified widths * @param height modified by * * public void Zoomimage (String srcfilename,string TAGFIlename,int width,int height) {try {bufferedimage bi = imageio.read (new File (Srcfilename)); 
     BufferedImage tag=new bufferedimage (width,height, BUFFEREDIMAGE.TYPE_INT_RGB); 
     Tag.getgraphics (). DrawImage (bi, 0, 0, width, height, null); 
     Imageio.write (tag, "JPG", new File (Tagfilename));//Paint} catch (IOException e) {e.printstacktrace ();  /** * Scaling image (scaled by height and width) * @param srcimagefile source image file Address * @param result scaled image address * @param Height scale after the width of the zoom * @param widths * @param BB ratio does not need to filler: true for filler; 
   False is not filler; */public void scale (string srcimagefile, string result, int height, int width, boolean bb) {try {double Ratio = 0.0; 
      Scaling file F = new file (srcimagefile); 
      BufferedImage bi = imageio.read (f); Image itemp = bi.getscaledinstance (width, height, bi.) 
      Scale_smooth); Calculate scale if (bi.getheight () > height) | | (Bi.getwidth () > width)) {if (bI.getheight () > Bi.getwidth ()) {ratio = (new Integer (height)). Doublevalue ()/Bi.getheight () 
        ; 
        else {ratio = (new Integer (width)). Doublevalue ()/bi.getwidth (); } affinetransformop op = new Affinetransformop (affinetransform. Getscaleinstance (ratio, ratio), null 
        ); 
      itemp = op.filter (bi, NULL); } if (BB) {//filler bufferedimage image = new BufferedImage (width, height, bufferedimage.type_int 
        _RGB); 
        Graphics2D g = image.creategraphics (); 
        G.setcolor (Color.White); 
        G.fillrect (0, 0, width, height); if (width = = itemp.getwidth (null)) G.drawimage (itemp, 0, (Height-itemp.getheight (NULL))/2, I 
        Temp.getwidth (NULL), itemp.getheight (null), color.white, NULL); else G.drawimage (itemp, (Width-itemp.getwidth (NULL))/2, 0, itemp.getwidth (null), itemp.gethe 
 Ight (NULL),             Color.White, NULL); 
        G.dispose (); 
      itemp = image; 
    } imageio.write ((bufferedimage) itemp, "JPEG", new File (result)); 
    catch (IOException e) {e.printstacktrace ();  }/** * Image cutting (at specified start coordinates and wide-high cut) * @param srcimagefile source image Address * @param image address after result slicing * @param x Target slice start coordinates x * @param y target slice start coordinates y * @param width target slice width * @param height target slice height/public void cut (String  Srcimagefile, String result, int x, int y, int width, int height) {try {//Read source image BufferedImage 
      BI = imageio.read (new File (Srcimagefile)); int srcwidth = Bi.getheight (); SOURCE graph width int srcheight = Bi.getwidth (); Source Diagram Height if (srcwidth > 0 && srcheight > 0) {image image = Bi.getscaledinstance (Srcwidth, SR 
        Cheight, Image.scale_default); The four parameters are the image start coordinates and the width high//namely: CropImageFilter (int x,int y,int width,int height) imagefilter crOpfilter = new CropImageFilter (x, y, width, height); 
                Image img = Toolkit.getdefaulttoolkit (). CreateImage (New FilteredImageSource (Image.getsource), 
        Cropfilter)); 
        BufferedImage tag = new BufferedImage (width, height, bufferedimage.type_int_rgb); 
        Graphics g = tag.getgraphics (); G.drawimage (IMG, 0, 0, width, height, null); 
        Draw the cut figure g.dispose (); 
      The output is file Imageio.write (tag, "JPEG", new file (result)); 
    } catch (Exception e) {e.printstacktrace (); 
    }///Get file name public String getfilename (multipartfile file, HttpServletRequest request,httpsession session) { 
    String File_path = Session.getservletcontext (). Getrealpath ("/") + "upload";  
    String fileName = File.getoriginalfilename (); 
    string[] Suffixnamearr = Filename.split ("\;"); 
    String suffixname = suffixnamearr[suffixnamearr.length-1]; String userName = Securitycontextholder.getcontext (). getauthentIcation (). GetName (); return GetTime () + username+ "." 
  +suffixname; //File Upload, return file path public String uploadfile (multipartfile file, HttpServletRequest request,httpsession session) throws 
    IOException {String File_path = Session.getservletcontext (). Getrealpath ("/") + "upload"; 
    String fileName = GetFileName (file,request,session);  
     
    File Tempfile = new file (File_path, fileName);  
    if (!tempfile.getparentfile (). exists ()) {Tempfile.getparentfile (). mkdir ();  
    } if (!tempfile.exists ()) {tempfile.createnewfile (); } file.transferto (Tempfile); 
     
    Writes the uploaded file to the file specified on the server.  
  return file_path + "\" + tempfile.getname ();  
  }/* public static File getFile (String filename) {return new file (file_path, filename); 
    }/Public String getTime () {Date date = new Date (); 
   SimpleDateFormat df = new SimpleDateFormat ("YYYYMMDDHHMMSS");//Set date format String nowtime = Df.format (date). toString (); return nowtime; 
 } 
}

This will be the picture to crop the picture path back to the page display

3. After that is the picture cut, picture cutting function I find a lot of plug-ins, the last lock Jcrop, but also because it's demo touched me (too good-looking), after the import file, in my here, I returned in the background of the page back to the image of the path after the Jcrop enabled, That is, Openjcrop () method, so that you can load the Jcrop plug-in, specifically you want to learn more about this cutting tool, please go to the official website to study carefully, I will not do too much talk.

Everybody, there's a big hole in here. is really a big pit, is to choose the picture, was Jcrop loaded img SRC can not be modified, this was the original card I long time, was jcrop loaded once Jcrop will generate a own edit object (my own understanding), This is not the same as the original IMG, until the end of a careful study of the API to find a way, the only way is to destroy this Jcrop, is Jcrop_api.destroy (), this has a lot of knowledge, I will hint that is to JCROP_ The API is declared as a global variable, and the following JS code is posted (and the HTML above is under a file):

<script type= "Text/javascript" > $ (function () {var jcrop_api; 
   
   }); 
     $ ("#file_upload"). Change (function () {$ ("#msg"). Text ("); 
     var ofile = $ (this) [0].files[0];  
       Determine the upload file size if (Ofile.size > 1*1024*1024) {$ ("#msg"). Text (' You have selected too large a file, please select an image file under 1M '). CSS (' Color ', ' red '); 
       $ (this). Val (""); 
     Return 
     }//Judgment type var filepath=$ (this). Val (); 
     var extstart=filepath.lastindexof ("."); 
     var ext=filepath.substring (extstart,filepath.length). toUpperCase (); if (ext!=). JPEG "&&ext!=". PNG "&&ext!=". 
        JPG ") {$ (" #msg "). Text (' Please select a valid image file (Jpg,png is allowed) '). CSS (' Color ', ' red '); 
        $ (this). Val (""); 
     Return 
      $ ("#fileUp"). Ajaxsubmit ({type: "POST", url: "/file/img/upload", DataType: "JSON", ContentType: "Application/json", success:function (parameter) {$ ("#target2"). attr (' src ', '/upload/' +para Meter.filename);
        $ ("#filePathInput"). Val ('/upload/' +parameter.filename); 
        if ($ ("#format"). Text () = "re-upload") {Jcrop_api.destroy ()} $ ("#format"). Text ("Re-uploading"); 
      Start Jcrop support Openjcrop ('/upload/' +parameter.filename); Error:function (data) {alert ("AJAX Transfer Error!!! 
      "); 
  }  
     }); 
   }); 
     function Photosummit () {//alert ($ ("#w"). Val () + "," +$ ("#h"). Val () + "," +$ ("#x"). Val () + "," +$ ("#y"). Val ()); 
     $ ("#fileUp"). attr ("Action", "/file/img/upload"). Submit (); if ($ ("#w"). Val () >0 && $ ("#h"). Val () >0) {$ ("#fileUp"). Ajaxsubmit ({type: POST), URL : "/file/img/cutandscale", DataType: "JSON", ContentType: "Application/json", Success:function ( Data) {$ ("#msg"). Text (' Upload avatar successful!!! 
           '). CSS (' Color ', ' red '); 
           Alert ($ ("#filePathInput"). Val ()); 
        Window.parent.back ($ ("#filePathInput"). Val ()); }, Error:funCtion (data) {alert ("AJAX Transfer Error!!! 
        "); 
     }  
      }); 
     }else{$ ("#msg"). Text (' Please use mouse to intercept picture '). CSS (' Color ', ' red '); Start Jcrop function Openjcrop (imgpath) {//boot Jcrop support var boundx,boundy, xsize = $ (' #p 
         
        Review-pane. Preview-container '). Width (), ysize = $ (' #preview-pane. Preview-container '). Height (); $ (' #target '). Jcrop ({minsize: [a], Onchange:updatepreview, Onselect:updatepreview, ASP Ectratio:xsize/ysize},function () {//Use the APIs to get the real image size var bounds = 
         This.getbounds (); 
         Boundx = Bounds[0]; 
         Boundy = bounds[1]; 
        Jcrop_api = this; 
        }); 
        Jcrop_api.setimage (Imgpath); 
          function Updatepreview (c) {if (parseint (C.W) > 0) {var rx = XSIZE/C.W; 
       
          var ry = ysize/c.h; $ (' #preview-PAne. Preview-container img '). CSS ({width:Math.round (RX * boundx) + ' px ', height:Math.round (RY * Boundy) + ' px ', marginleft: '-' + math.round (RX * c.x) + ' px ', margintop: '-' + math.round (ry * C. 
          Y) + ' px '}); 
          $ ("#w"). Val (C.W); 
          $ ("#h"). Val (c.h); 
          $ ("#x"). Val (c.x); 
         $ ("#y"). Val (C.Y); 
  } 
         }; 
 } </script>

This completes the editing function, and then we click Submit to upload the w,h,x,y parameters to the background.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.