通过 BufferedImage 和 ImageReader 实现图片裁剪功能
// 裁剪图片
private static void cutImage() throws IOException {
String type = "jpg";
// 裁剪的位置
int x = 100;
int y = 100;
int width = 200;
int height = 200;
// 文件地址
File file = new File("/Users/xx/a.jpg");
InputStream input = new FileInputStream(file);
ImageInputStream imageStream = null;
try {
// 图片类型 默认 jpg
String imageType = (null == type || "".equals(type)) ? "jpg" : type;
// 将图片转化为 imageReader
Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageType);
ImageReader reader = readers.next();
// 读入图片
imageStream = ImageIO.createImageInputStream(input);
reader.setInput(imageStream, true);
// 参数
ImageReadParam param = reader.getDefaultReadParam();
// 图片裁剪范围
Rectangle rect = new Rectangle(x, y, width, height);
param.setSourceRegion(rect);
// 裁剪出图片
BufferedImage bi = reader.read(0, param);
// 输出达到文件夹
ImageIO.write(bi, imageType, new File("/Users/xx/b.jpg"));
} catch (Exception e) {
} finally {
// 关闭stream
imageStream.close();
}
}