Java – The fastest way to check if an image is all white or transparent

The fastest way to check if an image is all white or transparent… here is a solution to the problem.

The fastest way to check if an image is all white or transparent

How can you effectively tell if a PNG contains only white and transparent pixels? The picture I entered is basically transparent with some handwritten notes on it. The identification must be very reliable. After loading the bitmap, my current code loops through all pixels, but it takes too long to execute. I’m looking for a better/faster solution.

public static boolean isEmpty(Bitmap bmp)
{
    int[] pixels = new int[bmp.getWidth() * bmp.getHeight()];
    bmp.getPixels(pixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
    for (int i : pixels)
    {
        if (!( Color.alpha(i) == 0 || (Color.blue(i) == 255 && Color.red(i) == 255 && Color.green(i) == 255)))
            return false;
    }
    return true;
}

Solution

Another idea might be:

1 – Shrink the image to a very small size (such as 100 x 100 pixels).
2 – Analyze each pixel color in the nested for loop (for y includes for x – and vice versa).
3 – If all these 10,000 pixels have an alpha of 0 (each time you check that the alpha of a pixel is 0, just increment with one counter), you can confirm that the image is completely transparent with a good approximation.

Related Problems and Solutions