1

您好,我想创建一个程序,它读取图像并在输出带有这样图像的 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;
            }
        }

};
4

2 回答 2

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;
            }
        }
于 2013-04-22T09:56:56.160 回答
1

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

尝试这样的事情:

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);
            }
        }
    }
};
于 2013-04-22T10:00:08.517 回答