简体   繁体   English

BufferedImage.getRGB中的坐标超出范围

[英]Coordinate out of bounds in BufferedImage.getRGB

I am trying to convert this PNG image by this method from an BufferedImage to an double array. 我试图通过此方法将此png图像从BufferedImage转换为双精度数组。

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)" “超出范围!在java.awt.image.BufferedImage.getRGB(未知源)处的sun.awt.image.ByteInterleavedRaster.getDataElements(未知源)”

The problem in your code is simply that you mixed up what i and j means, and what parameters getRGB(x, y) expects. 代码中的问题仅仅是,您混淆了ij含义以及getRGB(x, y)期望的参数。 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. 但是,(如VGR在他的评论中指出),使用更有意义的变量名是一种好习惯。 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 . 因为j是您的X坐标(在宽度上迭代),而i是您的Y(在高度上迭代),所以最好将它们命名为xy 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. 我认为错误是您的I和j变量变得大于高度和宽度。 Try changing the conditions of your for loops to: 尝试将for循环的条件更改为:

I <= height J <= width I <=高度J <=宽度

Instead of: 代替:

I < height J < widtb I <高度J <widtb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM