import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class ImgTool { private int startX; private int startY; private int width; private int height; /** * 源路径 */ private String srcPath; /** * 目标路径 */ private String tarPath; public static void main(String args[]){ ImgTool imgT = new ImgTool(); imgT.setStartX(100); imgT.setStartY(100); imgT.setHeight(200); imgT.setWidth(200); imgT.setSrcPath("农场.jpg"); imgT.setTarPath("d:/1.jpg"); imgT.cut(); } /** * 根据开始坐标,宽度和高度切图。 * 把图片读入内存缓冲区,然后再 * 根据具体坐标切取子图最后把子 * 图按规定的格式存入指定文件 */ public void cut(){ try { BufferedImage bufImg = ImageIO.read(new File(srcPath)); bufImg = bufImg.getSubimage(startX, startY, width, height); ImageIO.write(bufImg,"jpg",new File(tarPath)); } catch (Exception e) { e.printStackTrace(); } } public int getStartX() { return startX; } public void setStartX(int startX) { this.startX = startX; } public int getStartY() { return startY; } public void setStartY(int startY) { this.startY = startY; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } 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; } public String getTarPath() { return tarPath; } public void setTarPath(String tarPath) { this.tarPath = tarPath; } }