In the project, we need to do something like Avatar upload, image clipping function, OK to see the article below!
plugins required: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 Little Night Legends * @param path1 Picture Original path * @param path2 the path stored after cropping * @param x x axis * @param y y axis * @par Am W * @param h */public static void Cutimage (String path1,string path2,int x,int y,int w,int h) {FileInputStream fileInput Stream=null;imageinputstream Iis=null;try {//Read picture file, establish file input stream fileinputstream=new FileInputStream (path1);//create picture file stream Iterator iterator<imagereader> it = imageio.getimagereadersbyformatname ("jpg"); ImageReader reader=it.next ();// Get picture stream Build file stream Iis=imageio.createimageinputstream (fileinputstream);//Get Picture Default parameter Reader.setinput (IIS, True); Magereadparam Param=reader.getdefaultreadparam ();//define Crop area Rectangle rect=new Rectangle (x,y,w,h);p ARam.setsourceregion (rect); BufferedImage Bi=reader.read (0,param); Imageio.write (bi, "JPG", new File (path2));} catch (Exception e) {e.printstacktrace (); System.out.println ("cropping 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;//clipped after the picture path stored to the server string path2=relpath+ "/images/" +newfilename;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" >
, feel good, look at the following source, right?
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java implementation of picture clipping preview function