In the project, we need to do some similar avatar upload, picture clipping function, OK look at the following article!
Require plugins: jQuery jcrop
Back-end code:
Package org.csg.upload;
Import Java.awt.Rectangle;
Import Java.awt.image.BufferedImage;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.util.Iterator;
Import Javax.imageio.ImageIO;
Import Javax.imageio.ImageReadParam;
Import Javax.imageio.ImageReader;
Import Javax.imageio.stream.ImageInputStream; public class Upload {/** * @author the Legend of the night * @param path1 Picture Original path * @param path2 trimmed path * @param x x axis * @param y Y-Axis * @param w * @param h */public static void Cutimage (String path1,string path2,int x,int y,int w,int h) {File
InputStream Fileinputstream=null;
Imageinputstream Iis=null;
try {//Read the picture file, establish the file input stream fileinputstream=new FileInputStream (path1);
Create a picture of the file stream iterator iterator<imagereader> it = imageio.getimagereadersbyformatname ("jpg");
ImageReader Reader=it.next ();
Gets the picture stream to establish the text diagram file stream Iis=imageio.createimageinputstream (FileInputStream);
Gets the picture default parameter Reader.setinput (IIS, True); ImagereadparaM Param=reader.getdefaultreadparam ();
Define crop area Rectangle rect=new Rectangle (x,y,w,h);
Param.setsourceregion (rect);
BufferedImage Bi=reader.read (0,param);
Imageio.write (BI, "JPG", new File (path2));
catch (Exception e) {e.printstacktrace ();
System.out.println ("crop failed");
}finally{try {if (fileinputstream!=null) {fileinputstream.close ();
} if (Iis!=null) {iis.close ();
} catch (IOException e) {e.printstacktrace ();
}
}
}
}
Access code:
<%@ page language= "java" import= "java.util.*,org.csg.upload.*" pageencoding= "Utf-8"%>
<%
// The relative path of the picture
String imagpath=request.getparameter ("Imgpath");
String Relpath=request.getrealpath ("/")//Get Picture Server absolute address
string newfilename=new Date (). GetTime () + ". jpg";
The actual picture path
String Path1=relpath+imagpath;
The image path
String path2=relpath+ "/images/" +newfilename that is stored to the server after cropping;
int X=integer.parseint (Request.getparameter ("X"));
int Y=integer.parseint (Request.getparameter ("Y"));
int W=integer.parseint (Request.getparameter ("w"));
int H=integer.parseint (Request.getparameter ("H"));
try{
upload.cutimage (path1, path2, X, Y, W, h);
Out.print ("
JSP Code:
<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
Effect Chart:
The above is the entire content of this article, I hope you can enjoy.