简体   繁体   English

检查图像在Java中是全白还是完全透明

[英]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 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));

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. 使用PixelGrabber获取所有像素。 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 http://i.stack.imgur.com/GqRSB.png : 网址为http://i.stack.imgur.com/GqRSB.png的白色图片:
    在此处输入图片说明
    System.out.println(isValid("http://i.stack.imgur.com/GqRSB.png"));
    Output : false 输出:false

  2. Transparent Image with url http://i.stack.imgur.com/n8Wfi.png : 网址为http://i.stack.imgur.com/n8Wfi.png的透明图像:
    在此处输入图片说明
    System.out.println(isValid("http://i.stack.imgur.com/n8Wfi.png"));
    Output : false 输出:false

  3. A Valid image with url http://i.stack.imgur.com/Leusd.png : 网址为http://i.stack.imgur.com/Leusd.png的有效图片:
    在此处输入图片说明
    System.out.println(isValid("http://i.stack.imgur.com/Leusd.png"));
    Output : true 输出:真

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM