我在尝试从图像中读取像素时收到 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;
}
最佳答案
您没有考虑每个像素的波段数 - 每个像素由多个波段( channel ,例如 TYPE_INT_ARGB 图像的红色、绿色、蓝色、Alpha)组成,具体取决于图像类型。您分配的数组大小必须为(像素宽度 * 像素高度 * 波段数):
int numBands = bi.getData().getNumBands();
inputFace = new double[imageWidth * imageHeight * numBands];
这将为您提供一个数组,其中包含每个像素的每个 channel 的所有值。
关于java - 尝试从图像中读取像素时出现 ArrayIndexOutOf BoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18791191/