Marcelo Assis
Marcelo Assis

Reputation: 5194

Looping through image pixels is crashing my program

I started to work into a little image processing software. Currently I just need to set a image to black & white and loop through its pixels and generate a report of a counter, coordinates and color of each pixel (#,x,y,color).

It works fine with tiny images I create just to test, but when I use a real picture, it takes several minutes or even crash my software. My code inside the loop seems to be simple to be crashing.

Any tip on how can I improve it? Thanks in advance!

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;
}

Upvotes: 1

Views: 82

Answers (1)

Trinimon
Trinimon

Reputation: 13957

This is probably your problem

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

Use a StringBuilder instead:

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

....

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

Check the StringBuilder documentation for details. Additionally, you could try to reduce the number of objects being created. So for instance replace:

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")));

Good luck! :)

Upvotes: 3

Related Questions