使用Image的每个像素的RGB值填充ArrayList

时间:2013-04-22 09:32:01

标签: java image excel arraylist

你好我想创建一个读取图像的程序,然后输出一个像这样的图像的excel ---> http://www.boydevlin.co.uk/images/screenshots/eascreen04.png

为了实现这一点,我想我必须将图像中每个像素的rgb值读取到ArrayList 我想按以下顺序保存它

示例5x5px图像

01,02,03,04,05
06,07,08,09,10  
11,12,13,14,15
.......

我已经有了这个,但它没有正确运作有人可以用算法帮助我

    public class Engine {

    private int x = 0;
    private int y = 0;
    private int count = 50;
    private boolean isFinished = false; 
    ArrayList<Color> arr = new ArrayList<Color>();

    public void process(){
        BufferedImage img = null;
        try {
            img = ImageIO.read(new File("res/images.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("img file not found");
        }

        while(isFinished = false){
        int rgb = img.getRGB(x, y);
        Color c = new Color(rgb);
        arr.add(c);
        System.out.println("y:"+ y);
        x++;}
        if(x == 49){
            y++;
            x = 0;
            }else if(x == 49 && y == 49){
                isFinished = true;
            }
        }

};

2 个答案:

答案 0 :(得分:2)

首先while循环

中有错误

将其转换为:

while (isFinished=false)

while (isFinished==false) 

:使用for循环代替while循环

for (int x = 0; x < img.getWidth(); x++) {
            for (int y = 0; y < img.getHeight(); y++) {
                int rgb = img.getRGB(x, y);
                Color c = new Color(rgb);
                arr.add(c);
            }

        }

如果你想通过while循环使用它,试试这个:

while (isFinished == false) {
            int rgb = img.getRGB(x, y);
            Color c = new Color(rgb);
            arr.add(c);
            x++;
            if (x == img.getWidth()) {
                y++;
                x = 0;
            } else if (x == img.getWidth() - 1 && y == img.getHeight() - 1) {
                isFinished = true;
            }
        }

答案 1 :(得分:1)

你需要知道,如果图像变大,ArrayList会非常大,更好地使用普通数组(你知道.. []),并使它成为两个dimmensional。 如果您可以创建excel并且不将所有数据保存在数组中,那么只需在将数据写入控制台的地方设置适当的值即可。 我没有测试过代码,但应该没问题。 如果您发布任何Exception,请发布其内容,以便我们提供帮助。

尝试类似的事情:

public class Engine {

    private int x = 0;
    private int y = 0;
    ArrayList<Color> arr = new ArrayList<Color>();

    public void process() {
        BufferedImage img = null;
        try {
            img = ImageIO.read(new File("res/images.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("img file not found");
        }

        for(int x=0;x<img.getWidth();x++){
            for(int y=0;y<img.getHeight();y++){
                int rgb = img.getRGB(x, y);
                Color c = new Color(rgb);
                arr.add(c);
                System.out.println("x: "+ x + " y:" + y +" color: " + c);
            }
        }
    }
};
相关问题