I am trying to convert this PNG image by this method from an BufferedImage to an double array.
public double[][] bufferedToArray(File pngImage)
{
double[][] imageMatrix= null;
try {
final BufferedImage image = ImageIO.read(pngImage);
int height= image.getHeight();
int width= image.getWidth();
imageMatrix= new double[height][width];
System.out.println("Matriz Máximo i: " + imageMatrix.length +
"Matriz Máximo j: " + imageMatrix[0].length );
for(int i=0;i<height;i++){
for(int j=0;j<width;j++){
//System.out.println("i atual: "+i+" j atual: "+j);
imageMatrix[i][j] = image.getRGB(i, j); //The error is in this line.
//System.out.println("matrizImagem["+i+"]["+j+"] Inserido");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return imageMatrix;
}
Even I define array to exactly size of the image height and width I am getting the error of the bounds, when it's almost completing the looping. I don't know why.
"Coordinate out of bounds! at sun.awt.image.ByteInterleavedRaster.getDataElements(Unknown Source) at java.awt.image.BufferedImage.getRGB(Unknown Source)"
The problem in your code is simply that you mixed up what i
and j
means, and what parameters getRGB(x, y)
expects. Your code will (accidentally) work for square images, only.
Changing the line:
imageMatrix[i][j] = image.getRGB(i, j); //The error is in this line.
to:
imageMatrix[i][j] = image.getRGB(j, i);
Will solve the problem.
It is, however (as VGR points out in his comment), good practice to use more meaningful variable names. As j
is your X coordinate (iterating over the width), and i
is your Y (iterating over the height), it would probably be better to name them so, x
and y
. That would make the error much easier to spot, especially when consulting the documentation.
I imagine the error is that your I and j variables are becoming larger than the height and width. Try changing the conditions of your for loops to:
I <= height J <= width
Instead of:
I < height J < widtb
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.