线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:坐标超出界限

时间:2014-12-03 05:33:59

标签: java bufferedimage javax.imageio

BufferedImage image = ImageIO.read(new File(img path));  

int width = image.getWidth();
int height = image.getHeight();
int[][] result = new int[height][width];

for (int row = 0; row < height; row++) {
  for (int col = 0; col < width; col++) {
     result[row][col] = image.getRGB(row, col);
  }
}

这是我得到的例外:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at sun.awt.image.ByteInterleavedRaster.getDataElements(ByteInterleavedRaster.java:301)
at java.awt.image.BufferedImage.getRGB(BufferedImage.java:871)
at PlantExtraction.main(PlantExtraction.java:46)

如何删除这些例外?

1 个答案:

答案 0 :(得分:4)

代码

image.getRGB(row, col); 

应该是

image.getRGB(col, row);

正如文件所说:

getRGB(int x, int y)

Documentation

(您的col值正在运行width - 这是x - 图片的最大值,因此请col使用x和{{ 1}} row