Search code examples
javabufferedimagejavax.imageio

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds


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);
  }
}

and this is the exception I get :

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)

How can I remove these exceptions ?


Solution

  • The code

    image.getRGB(row, col); 
    

    Should be

    image.getRGB(col, row);
    

    As the documentation says:

    getRGB(int x, int y).

    Documentation

    (your col value is running upto width - which is the x-maximum of the image, so use col for x and row for y)