- 调用ImageIO.read获取图片以及原图的宽度、高度
- 通过双层for循环获取黑色字所在矩阵的上下左右四个极值
- 调用BufferedImage 的getSubimage方法裁剪指定矩阵
- 调用ImageIO.write方法生成裁剪后的图片
使用getSubimage方法截取极值区域
BufferedImage bufferedImage;
try {
bufferedImage = ImageIO.read(new File("/Users/macbookpro/Desktop/20231216-105805.png"));
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
System.out.println("原图片宽度" + width);
System.out.println("原图片高度" + height);
int[] arr = bufferedImageToIntArray(bufferedImage, width, height);
BufferedImage newBufferedImage = bufferedImage.getSubimage(arr[0], arr[1], arr[2], arr[3]);
ImageIO.write(newBufferedImage, "png", new File("/Users/macbookpro/Desktop/test1.png"));
} catch (IOException e) {
throw new RuntimeException(e);
}
下面这段代码可以获取到除白色和透明色之外,有效内容区的范围极值
private static int whiteBg = new Color(255, 255, 255).getRGB();
private static int transparentBg = new Color(0, 0, 0,0).getRGB();
public static int[] bufferedImageToIntArray(BufferedImage image, int width, int height) {
try {
int rgb = 0;
int x1 = width;
int y1 = height;
int x2 = 0;
int y2 = 0;
int temp1 = 0;
int temp2 = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
rgb = image.getRGB(i, j);
if (rgb != whiteBg&&rgb != transparentBg) {
temp1 = i;
temp2 = j;
if (x1 >= temp1) {
x1 = temp1;
}
if (x2 <= temp1) {
x2 = temp1;
}
if (y2 <= temp2) {
y2 = temp2;
}
if (y1 >= temp2) {
y1 = temp2;
}
}
}
}
return new int[] {x1, y1, x2 - x1, y2 - y1};
} catch (Exception e) {
e.printStackTrace();
}
return null;
}