Use Jcrop for portrait cutting

Source: Internet
Author: User
Tags crop image

The project needs to do a head capture function, similar to the QQ Avatar interception function. Search the Internet, and finally use the jquery plugin jcrop to intercept,

In the background to do picture cutting.

The principle of Avatar interception: use Jcrop in the foreground to get the x-axis, y-axis, slice height, slice width of the slice, and then pass the four values

Console In the background to be enlarged processing: The plane will be enlarged N times, n= original/front display of the head. i.e. X = x* Wide chart/front width, Y = y* original image Height/front

Fig height, W = w* original Wide chart/front figure width, H = h* Image Height/front figure height.

Instance:

Jsp:

   	<div id= "Cutimage" style= "Display:none;" >
		<div class= "bigimg" style= "float:left;" >
			
		</div> <div id="
		preview_box " class= "Previewimg" >
			
		</div>
			
		<div >
		<form action= "" method= "Post" id= "Crop_form" >
		     <input type= "hidden" id= "Bigimage" name= "Bigimage"/ >
	              <input type= "hidden" id= "x" name= "x"/> <input "type="
	              hidden "y" id= "y" name=
	              < Input type= "hidden" id= "W" name= "" W "/> <input type="
	              hidden "id=" H "name=" H "/> <p><input
	              Type= "button" value= "Confirm" id= "Crop_submit"/></p>
	        </form>
	   </div>
	</div>

Style: Large and small show all need to fixed height, width, because the background needs to be enlarged processing. namely:

Then the Jcrop is used. We need to download jcrop:http://deepliquid.com/content/jcrop.html before using Jcrop.

After the download of the compressed package can be seen three folders and a index.html file,/CSS placed under the JCorp style file,/demo placed under a few simple examples (index.html referenced in the link is placed in this folder),/ JS placed is the most important script file in the JCorp. We only need to use three files: jquery. Jcrop.css, jquery. Jcrop.js, Jquery.js

How to use:

Crop image
function cutimage () {
	$ ("#srcImg"). Jcrop ({
			aspectratio:1,
			onchange:showcoords,
			onselect:showcoords,
			minsize: [200,200]
		});
		A simple event handler that responds to the Onchange,onselect event and invokes
		function showcoords (obj) {
			$ ("#x") according to the above Jcrop. Val (obj.x);
			$ ("#y"). Val (obj.y);
			$ ("#w"). Val (OBJ.W);
			$ ("#h"). Val (obj.h);
			if (parseint (OBJ.W) > 0) {
				//calculates the scale of the preview area picture scaling, gets the
				var rx = $ ("#preview_box") by calculating the width (and height) of the display area versus the trimmed width (and height). Width ()/OBJ.W;
				var ry = $ ("#preview_box"). Height ()/obj.h;
				Control the picture's style and display
				$ ("#previewImg") by proportional value. css ({
					width:Math.round (RX * $ ("#srcImg"). Width ()) + "px",// Preview picture width is the product
					height:Math.round (RX * $ ("#srcImg") that calculates the proportional value with the original picture width. Height ()) + "px"///Preview picture height is the product
					of the calculated proportional value and the original picture height MarginLeft: "-" + Math.Round (RX * obj.x) + "px",
					margintop: "-" + math.round (ry * obj.y) + "px"
				});
		}
}


Before using Jcrop, you must first initialize the $ (""). Jcrop (), otherwise no effect.

There is also a method of calling,

	var API = $. Jcrop (' #cropbox ', {
                  onchange:showpreview,
                  onselect:showpreview,
                  aspectratio:1
           });


This approach is to assign a Jcrop-generated object to a global variable, which is easier to do.

Through the above JS, the x axis coordinates, y axis coordinates, height h, Width w This four values passed to the background, the background only need according to these four values

Zoom in and then cut.

Action

	/** * Cutting head/Public String cutimage () {/* * Get Parameters * X,y,w,h,bigimage/HttpServletRequest request = (h
		ttpservletrequest) Actioncontext.getcontext () (). get (Servletactioncontext.http_request);
		int x = integer.valueof (Request.getparameter ("X"));
		int y = integer.valueof (Request.getparameter ("Y"));
		int w = integer.valueof (Request.getparameter ("w"));
		int h = integer.valueof (Request.getparameter ("H"));          
		
		String bigimage = Request.getparameter ("Bigimage");
		Get file True path//get filename string[] imagenames = Bigimage.split ("/");
		String imagename = imagenames[imagenames.length-1];
		
		File official path String ImagePath = Getsavepath () + "\" +imagename;
		Cut picture Imagecut imagecut = new Imagecut ();
		
		Imagecut.cutimage (ImagePath, X, Y, W, h);
		After the avatar crop is finished, save the picture path to the user UserBean UserBean = (UserBean) request.getsession (). getattribute ("UserBean");
		Userbean.setuserphoto (Bigimage);
		Save Avatar Usercenterservice centerservice = new Usercenterservice (); Centerservice.updaTephoto (UserBean);
		
		Saves the modified user to the session request.getsession (). setattribute ("UserBean", UserBean);
	return "Updatephoto"; }
}


         Crop Picture Tools class: Imagecut.java

public class Imagecut {/** * picture cut * @param imagepath original address * @param x target slice coordinate x axis start * @param y target slice coordinate y-axis start *
			@param w Target Slice width * @param h target Slice height */public void Cutimage (String imagepath, int x, int y, int w,int h) {try {
			Image img;
			ImageFilter Cropfilter;
			Read source image bufferedimage bi = imageio.read (new File (ImagePath));      int srcwidth = Bi.getwidth ();    SOURCE graph width int srcheight = Bi.getheight (); Source diagram Height//packages graph size greater than slice size, then cut if (srcwidth >= w && srcheight >= h) {Image image = Bi.getscal
			    
			    Edinstance (Srcwidth, Srcheight,image.scale_default);
                int x1 = x*srcwidth/400;
                int y1 = y*srcheight/270;
                int w1 = w*srcwidth/400;
                
                int h1 = h*srcheight/270;
                Cropfilter = new CropImageFilter (x1, y1, W1, H1);
                img = Toolkit.getdefaulttoolkit (). CreateImage (New FilteredImageSource (Image.getsource (), cropfilter)); BuffEredimage tag = new BufferedImage (W1, H1,BUFFEREDIMAGE.TYPE_INT_RGB);
                Graphics g = tag.getgraphics (); G.drawimage (IMG, 0, 0, NULL);
                Draw the reduced figure g.dispose ();
			The output is file Imageio.write (tag, "JPEG", new File (ImagePath));
		} catch (IOException e) {e.printstacktrace (); }
	}
}

Effect Chart:

When you click on the confirmation, you will generate the corresponding picture under the specified path:


Over..

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.