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

faz*_*man 3 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的例外:

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)
Run Code Online (Sandbox Code Playgroud)

我怎样才能消除这些异常?

dog*_*ose 6

代码

image.getRGB(row, col); 
Run Code Online (Sandbox Code Playgroud)

应该

image.getRGB(col, row);
Run Code Online (Sandbox Code Playgroud)

正如文档所说:

getRGB(int x, int y)

文档

(您的col值正在运行到width- 这是x图像的最大值,因此请使用colforxrowfor y