T A T A - 8 days ago 5
Java Question

Coordinate out of bounds Exception

Im trying to write RGB Data from a BufferedImage into an Array using the image raster, but Im getting a Coordinate out of bounds Exception that I cant figure out:

int height = img.getHeight();
int width = img.getWidth();

Raster R = img.getData();
double[] output = new double[3];


double[][][] pixel = new double[3][255][255];

for(int i=0;i<height;i++){
for(int j=0;j<width;j++){
R.getPixel(i,j,output);
pixel[0][i][j] = output[0];
pixel[1][i][j] = output[1];
pixel[2][i][j] = output[2];


It is supposed to write the pixel value with coordinates
(i,j)
for red into
pixel[0][i][j]
, for green into
[1][i][j]
and blue into
pixel[2][i][j]
.

Im getting the Exception for the Line:

R.getPixel(i,j,output);


Stacktrace using an Image with height 1 and width 2:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
at java.awt.image.ComponentSampleModel.getSampleDouble(Unknown Source)
at java.awt.image.SampleModel.getPixel(Unknown Source)
at java.awt.image.Raster.getPixel(Unknown Source)
at Color_Histogram.calculate(Color_Histogram.java:43)
at Color_Histogram.main(Color_Histogram.java:83)

Answer

this line is wrong

double[][][] pixel = new double[3][255][255];

it should be

double[][][] pixel = new double[3][height][width];