有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我调用了一个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));

共 (1) 个答案

  1. # 1 楼答案

    你必须检查所有像素,以检查你的图像是全白还是全透明。使用PixelGrabber获取所有像素。如果发现任何非全透明或非白色像素,则图像有效。以下是代码:

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

    您应该调整图像的大小以解决性能问题,这样您就不会遍历所有像素:

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

    注意:调整大小可能会忽略可能包含白色以外颜色的小区域。因此这个算法失败了。但这种情况很少发生

    编辑:
    以下是以下图像的测试运行:

    1. 带有url http://i.stack.imgur.com/GqRSB.png的白色图像:
      enter image description here
      System.out.println(isValid("http://i.stack.imgur.com/GqRSB.png"));
      输出:假

    2. 带有url http://i.stack.imgur.com/n8Wfi.png的透明图像:
      enter image description here
      System.out.println(isValid("http://i.stack.imgur.com/n8Wfi.png"));
      输出:假

    3. url为http://i.stack.imgur.com/Leusd.png
      的有效图像 enter image description here
      System.out.println(isValid("http://i.stack.imgur.com/Leusd.png"));
      输出:真