不废话,直接贴代码
/**
* @Title: ImageUtils
* @Description: 截取图片
* @author TimBrian
* @since Jan 15, 2019 4:19:16 PM
* @param imgPath
* @param subPath
* @param fileType
* @param x Rectangle左上角的X Rectangle
* @param y Rectangle左上角的Y Rectangle
* @param height Rectangle的高度
* @param width 宽度为 Rectangle
* @throws IOException
*/
public static void cutImage(String imgPath, String subPath, String fileType, int x, int y, int height ,int width) throws IOException {
File f = new File(imgPath);
File t = new File(subPath);
if (t.exists()) {
t.delete();
}
//图片输入流
ImageInputStream iis = ImageIO.createImageInputStream(f);
//图片读取器
Iterator<ImageReader> it = ImageIO.getImageReaders(iis);
if (it.hasNext()) {
ImageReader r = it.next();
//设置输入流
r.setInput(iis, true);
System.out.println("格式=" + r.getFormatName());
System.out.println("宽=" + r.getWidth(0));
System.out.println("高=" + r.getHeight(0));
//读取参数
ImageReadParam param = r.getDefaultReadParam();
//创建要截取的矩形范围
Rectangle rect = new Rectangle(x, y, width, height);
//设置截取范围参数
param.setSourceRegion(rect);
//读取截图数据
BufferedImage bi = r.read(0, param);
//保存图片
ImageIO.write(bi, fileType, t);
}
}
当然,也可以以流的形式来操作文件