Java 通过图像像素循环正在破坏我的程序

Java 通过图像像素循环正在破坏我的程序,java,image,performance,swing,image-processing,Java,Image,Performance,Swing,Image Processing,我开始研究一个小的图像处理软件。目前,我只需要将图像设置为黑白并循环其像素,然后生成计数器报告、每个像素的坐标和颜色(#,x,y,color) 它适用于我只是为了测试而创建的微小图像,但当我使用真实图像时,它需要几分钟甚至使我的软件崩溃。我在循环中的代码似乎很容易崩溃 有关于如何改进的提示吗?提前谢谢 void processImage(BufferedImage image) { exportStr = "#,x,y,color"+ newline;

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

它适用于我只是为了测试而创建的微小图像,但当我使用真实图像时,它需要几分钟甚至使我的软件崩溃。我在循环中的代码似乎很容易崩溃

有关于如何改进的提示吗?提前谢谢

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;
}
void进程映像(buffereImage映像){
exportStr=“#,x,y,color”+换行符;
颜色c=新颜色(0);
int imgW=image.getWidth();
int imgH=image.getHeight();
矩阵=新整数[imgW][imgH];
int currentPx=1;
对于(int x=0;x
这可能是您的问题

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

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

....

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

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

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

祝你好运!:)

为什么要使用
matrix
array?您也可以在不使用此数组的情况下导出字符串。@Braj,稍后我将需要该矩阵,尽管我现在不使用StringBuilder,但它确实提高了很多性能。谢谢由于
getRGB()
返回int,我使用了
if(image.getRGB(x,y)=Color.WHITE)
if(image.getRGB(x, y).equals(...))

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