将每个像素的颜色添加到ArrayList - java

问题描述 投票:-2回答:2

我想将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

我做错了什么?

java indexoutofboundsexception
2个回答
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());
        }
    }

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值的信息。

© www.soinside.com 2019 - 2024. All rights reserved.