我想将 Image
的每个像素的红色值添加到 ArrayList
。
这是我的代码:
BufferedImage image = null;
try {
image = ImageIO.read(imageFile);
} catch(IOException e) {
e.printStackTrace();
}
ArrayList<List<List<Integer>>> colors = new ArrayList<List<List<Integer>>>();
for ( int i = 0; i < image.getHeight(); i++ ) {
for ( int j = 0; j < image.getWidth(); j++ ) {
colors.get(i).get(j).add(new Color(image.getRGB(i, j)).getRed());
}
}
但我收到此错误:Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
。
我做错了什么?
答案 0 :(得分:1)
我认为您只需要一个列表列表来表示像素的二维性质(您的货币有列表列表)。每次迭代每个高度像素时,您应该创建一个新的像素,如下所示。
List<List<Integer>> colors = new ArrayList<List<Integer>>();
for ( int i = 0; i < image.getHeight(); i++ ) {
List<Integer> rowOfColours = new ArrayList<Integer>();
colors.add(rowOfColors);
for ( int j = 0; j < image.getWidth(); j++ ) {
rowOfColours.add(new Color(image.getRGB(i, j)).getRed());
}
}
答案 1 :(得分:0)
使用PillHead的答案。如果以后想要获得整个像素,请稍微改变代码:
for ( int i = 0; i < image.getHeight(); i++ ) {
List<Integer> rowOfPixelData = new ArrayList<Integer>();
colors.add(rowOfPixelData);
for ( int j = 0; j < image.getWidth(); j++ ) {
rowOfPixelData.add(image.getRGB(i, j));
}
}
从那里你可以提取你想要的值。 This website有很多关于如何从image.getRGB(i, j)
返回的整数中获取红色,绿色,蓝色和Alpha值的信息。