/**
* 将单张图片多张内容裁剪
*
* @param originalImagePath 原始图像路径
* @param cutParam 裁剪参数
*/
public static String cropImage(String originalImagePath, JSONObject cutParam) {
BufferedImage image = null;
String fileName, parentPath, suffix;
try {
File file = new File(originalImagePath);
// 文件夹
parentPath = file.getParent();
fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf("."));
// 获取文件后缀
suffix = originalImagePath.substring(originalImagePath.lastIndexOf(".") + 1);
image = ImageIO.read(new File(originalImagePath));
} catch (IOException e) {
throw new MyException(e.getMessage());
}
// 左上角X坐标
Integer leftUpX = cutParam.getInteger("leftUpX");
// 左上角Y坐标
Integer leftUpY = cutParam.getInteger("leftUpY");
// 右下角X坐标
Integer rightDownX = cutParam.getInteger("rightDownX");
// 右下角Y坐标
Integer rightDownY = cutParam.getInteger("rightDownY");
if (leftUpX >= image.getWidth() || leftUpY >= image.getHeight() ||
rightDownX > image.getWidth() || rightDownY > image.getHeight()) {
throw new MyException("Invalid cropping coordinates.");
}
// 裁剪后的图像
BufferedImage subimage = image.getSubimage(leftUpX, leftUpY, rightDownX - leftUpX, rightDownY - leftUpY);
// 裁剪后的单个文件路径
String rectanglePath = parentPath + "/" + fileName + "_" + cutParam.getString("index") + "." + suffix;
File rectangleFile = new File(rectanglePath);
FileUtil.createDir(rectangleFile.getParent());
try (ImageOutputStream ios = new FileImageOutputStream(rectangleFile)) {
ImageIO.write(subimage, suffix, ios);
} catch (IOException e) {
throw new MyException(e);
} catch (Exception e) {
e.printStackTrace();
}
return rectanglePath;
}
测试demo
public static void main(String[] args) {
String path = "D:/单图多内容.png";
JSONObject cutParam = new JSONObject();
// 左上角X坐标
cutParam.put("leftUpX", 736);
// 左上角Y坐标
cutParam.put("leftUpY", 0);
// 右下角X坐标
cutParam.put("rightDownX", 1528);
// 右下角Y坐标
cutParam.put("rightDownY", 505);
cutParam.put("index", 0);
try {
cropImage(path, cutParam);
} catch (Exception e) {
}
}