0

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)"

JamesB
  • 569
  • 1
  • 9
  • 31
  • 1
    Instead of `i` and `j`, use `y` and `x` respectively for your loop variables. Then read the [documentation for getRGB](https://docs.oracle.com/javase/9/docs/api/java/awt/image/BufferedImage.html#getRGB-int-int-). The problem should become clear. – VGR Dec 01 '17 at 21:17

2 Answers2

1

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.

Harald K
  • 26,314
  • 7
  • 65
  • 111
-2

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

Neytorokx
  • 7
  • 2