fangli
fangli

Reputation: 117

Check if an image is all white or fully transparent in Java

I was calling a url to get image store locally and it's already working, but I'm just want to make sure if the image all white or fully transparency, so that i can skip the image.

URL url = new URL(logoUrl);
InputStream is = url.openStream();
String fileName = logoUrl.substring(logoUrl.lastIndexOf('/') + 1);
//call other service to upload image as byte array.
uploadService.writeFile(request, fileName, IOUtils.toByteArray(is));

Upvotes: 1

Views: 4237

Answers (1)

afzalex
afzalex

Reputation: 8652

You will have to check all the pixels to check if your image is all white or all transparent. Use PixelGrabber to get all pixels. And if any non fully transparent or non white pixel is found, the image is valid. Here is the code :

public static boolean isValid(String imageUrl) throws IOException, InterruptedException {
    URL url = new URL(imageUrl);
    Image img = ImageIO.read(url);
    //img = img.getScaledInstance(100, -1, Image.SCALE_FAST);
    int w = img.getWidth(null);
    int h = img.getHeight(null);
    int[] pixels = new int[w * h];
    PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
    pg.grabPixels();
    boolean isValid = false;
    for (int pixel : pixels) {
        Color color = new Color(pixel);
        if (color.getAlpha() == 0 || color.getRGB() != Color.WHITE.getRGB()) {
            isValid = true;
            break;
        }
    }
    return isValid;
}

You should resize your image for performance issues, This way you will not iterate through all the pixels :

img = img.getScaledInstance(300, -1, Image.SCALE_FAST);

Note : resizing can miss small area that might contain color other than white color. Thus failing this algorithm. But it will rarely happen

Edit :
Here is the test run for following images :

  1. White Image with url https://i.sstatic.net/GqRSB.png :
    enter image description here
    System.out.println(isValid("https://i.sstatic.net/GqRSB.png"));
    Output : false

  2. Transparent Image with url https://i.sstatic.net/n8Wfi.png :
    enter image description here
    System.out.println(isValid("https://i.sstatic.net/n8Wfi.png"));
    Output : false

  3. A Valid image with url https://i.sstatic.net/Leusd.png :
    enter image description here
    System.out.println(isValid("https://i.sstatic.net/Leusd.png"));
    Output : true

Upvotes: 2

Related Questions