【问题标题】:ArrayIndexOutOf BoundsException while trying to read pixels from an image尝试从图像中读取像素时出现 ArrayIndexOutOf BoundsException
【发布时间】:2013-09-13 16:37:43
【问题描述】:

我在尝试从图像读取像素时收到 ArrayIndexoutOfBoundsException。该代码返回某些图像的像素值,而不是其他图像的像素值。我尝试搜索网络,其中大多数是指从 0 到 n 的读取...

代码如下..任何帮助将不胜感激..

我尝试将图像保存在 bi 中,它被保存了..所以 bi 永远不会得到空值.. 我的图像尺寸始终是 125*150.. 我尝试在 inputFace 中打印值,但在那些不提供像素值的图像中,我什至在打印时都没有得到任何输出...... 分配内存后数组不会初始化为0吗??

提前致谢

private double[] getImageData(String imageFileName)  {

        BufferedImage bi = null;
        double[] inputFace = null;


        try{
            bi = ImageIO.read(new File(imageFileName));

        }catch(IOException ioe){

                    ioe.printStackTrace();
        }
        if (bi != null){
                       int imageWidth = bi.getWidth();
                       int imageHeight = bi.getHeight();
                       inputFace = new double[imageWidth * imageHeight];

                         bi.getData().getPixels(0, 0, imageWidth, imageHeight,inputFace);


                }
                else
                {
                    System.out.println("Null in bi");
                }


                return inputFace;

    }

【问题讨论】:

  • 你试过不预分配 inputFace 吗?正在做inputFace = bi.getData().getPixels(0, 0, imageWidth, imageHeight,inputFace);
  • 我也试过了,但它不起作用......

标签: java arrays exception bufferedimage indexoutofboundsexception


【解决方案1】:

您没有考虑每个像素的波段数 - 每个像素由多个波段(通道,例如 TYPE_INT_ARGB 图像的红色、绿色、蓝色、Alpha)组成,具体取决于图像类型。您分配的数组大小必须为(像素宽度 * 像素高度 * 波段数):

int numBands = bi.getData().getNumBands();
inputFace = new double[imageWidth * imageHeight * numBands];

这将为您提供一个数组,其中包含每个像素的每个通道的所有值。

【讨论】:

    猜你喜欢
    • 2011-10-09
    • 1970-01-01
    • 2012-03-29
    • 2020-02-07
    • 2012-06-19
    • 1970-01-01
    • 2017-01-02
    • 2016-08-13
    • 2012-06-21
    相关资源
    最近更新 更多