这是我的代码:
for (int ii = 0; ii <= 17; ii++) {
System.out.println(ii);
if(ii == 10) continue;
String name = String.valueOf(ii);
File pic = new File(name + ".jpg");
BufferedImage image = ImageIO.read(pic);
int w ;
int h ;
int x_max = 0;
int x_min = 1000;
int y_max = 0;
int y_min = 1000;
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
Color c = new Color(image.getRGB(i, j));
if(c.getBlue() == 0){
x_max = Math.max(x_max, i);
x_min = Math.min(x_min, i);
y_max = Math.max(y_max, j);
y_min = Math.min(y_min, j);
}
}
}
BufferedImage imagea = image;
image = imagea.getSubimage(x_min - 1, y_min - 1,x_max - x_min + 3 , y_max - y_min + 3);
h = Math.abs(y_max - y_min);
w = Math.abs(x_max - x_min);}
这是输出:
0
1
2
3
4
5
6
7
Exception in thread "main" java.awt.image.RasterFormatException: (x + width) is outside of Raster
at sun.awt.image.ByteInterleavedRaster.createWritableChild(Unknown Source)
at java.awt.image.BufferedImage.getSubimage(Unknown Source)
at element.main(element.java:41)
错误是关于&#34; getsubimage&#34;功能,但我不知道它的原因。 代码工作到第八个图像,并没有为它工作。 如何工作&#34; getsubimage&#34;函数在java?
答案 0 :(得分:1)
这一行:
image = imagea.getSubimage(x_min - 1, y_min - 1,x_max - x_min + 3 , y_max - y_min + 3);
假设生成的坐标距离左上边缘至少1个像素,偏离左边缘和下边缘3个像素。不要假设,或确保他们愿意。