循环显示图像像素会导致我的程序崩溃

时间:2014-04-23 21:40:29

标签: java image performance swing image-processing

我开始研究一个小小的图像处理软件。目前我只需将图像设置为黑色&白色并循环显示其像素,并生成每个像素(#,x,y,颜色)的计数器,坐标和颜色的报告。

它可以很好地处理我为测试而创建的小图像,但是当我使用真实图片时,它需要几分钟甚至崩溃我的软件。循环中的代码似乎很容易崩溃。

关于如何改进它的任何提示?提前谢谢!

void processImage(BufferedImage image) {
        exportStr = "#,x,y,color"+ newline;     

        Color c = new Color(0);
        int imgW = image.getWidth();
        int imgH = image.getHeight();
        matrix = new int[imgW][imgH]; 

        int currentPx = 1;

        for(int x=0; x < imgW; x++) 
        {
            for(int y=0; y < imgH; y++) 
            {
                c = new Color(image.getRGB(x, y));

                if(c.equals(Color.WHITE))
                { 
                    matrix[x][y] = 1;                   
                }

                String color = matrix[x][y]==1 ? "W" : "B";
                exportStr += formatStringExport(currentPx, x, y, color); // just concatenate values
                currentPx++;
            }
        }

        return img;
}

1 个答案:

答案 0 :(得分:3)

这可能是你的问题

exportStr += formatStringExport(currentPx, x, y, color);

改为使用StringBuilder

StringBuilder sb = new StringBuilder(imgW  * imgH * <String size per pixel>);

....

sb.append(formatStringExport(currentPx, x, y, color));

查看StringBuilder文档以获取详细信息。此外,您可以尝试减少正在创建的对象的数量。例如,替换:

c = new Color(image.getRGB(x, y));

String color = matrix[x][y]==1 ? "W" : "B";

by ...

if(image.getRGB(x, y).equals(...))

sb.append(formatStringExport(currentPx, x, y, (matrix[x][y]==1 ? "W" : "B")));
祝你好运! :)

相关问题