Package Com.up.util;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 Operateimage {private string Srcpath;//original path private string subpath;//target storage path private string ImageType;//Picture type private int x; private int y; private int width; Picture target width private int height; Picture target height public operateimage () {} public operateimage (String srcpath, int x, int y, int width, int height) {this.src Path = Srcpath; this.x = x; This.y = y; This.width = width; This.height = height; } public int getheight () {return height;} public void setheight (int height) {this.height = height;} Public String Getsrcpath () {return srcpath;} public void Setsrcpath (String srcpath) {this.srcpath = Srcpath; if (Srcpath! = null) {This.imagetype = srcpath.substring (Srcpath.indexof (".") +1, Srcpath.length ()); }} public String Getsubpath () {return subpath;} public void Setsubpath (String subpath) {this.subpath = subpath;} public int getwidth () {return width;} public void setwidth (int width) {this.width = width;} public int GetX () {return x;} public void SetX (int x) {this.x = x;} public int GetY () {return y;} public void sety (int y) {this.y = y;} Public String Getimagetype () {return imageType;} public void Setimagetype (String imageType) {this.imagetype = ImageType;} public Boolean cut () throws IOException {FileInputStream is = null; Imageinputstream IIS = NULL; Boolean bol = false; try {is = new FileInputStream (Srcpath); Iterator<imagereader> it = imageio.getimagereadersbyformatname (This.imagetype); ImageReader reader = It.next (); IIS = Imageio.createimageinputstream (IS); Reader.setinput (IIS, True); Imagereadparam param = Reader.getdefaultreadparam (); RectanglE rect = new Rectangle (x, y, width, height); Param.setsourceregion (rect); BufferedImage bi = reader.read (0, param); Cut file o = new file (Srcpath) if the actual height is greater than the target height or the actual width is greater than the target width; BufferedImage bii = Imageio.read (o); int itempwidth = Bii.getwidth (); Actual width int itempheight = Bii.getheight (); Actual height if (itempheight > height) | | (Itempwidth > width)) {imageio.write (BI, This.imagetype, new File (subpath)); Bol = true; }} finally {if (is = null) is.close (); if (IIS! = null) iis.close (); } return BOL; } public static void Main (string[] args) {operateimage o = new Operateimage ("E:\\testdata\\1.jpg", 0, 0, 100, 100); O.setsubpath ("e:\\testdata\\2.jpg"); O.setimagetype ("JPG"); try {o.cut (); } catch (IOException e) {e.printstacktrace (); } }}
Java Upload Picture Clipping tool class