简体   繁体   English

如何在Java中使PNG的白色透明?

[英]How to make the white of a PNG transparent in Java?

I would like to know how to implement the following makeWhiteTransparent() below so that it takes a file and only makes the white pixels transparent in my existing PNG. 我想知道如何在下面实现下面的makeWhiteTransparent() ,以便它获取一个文件,并且只在我现有的PNG makeWhiteTransparent()白色像素透明。 That is ONLY the perfectly white pixels (#FFFFFF). 那只是完美的白色像素(#FFFFFF)。

public static void main(String[] args)
{
    File pngFile = new File(pathToPngFile);
    File outputPngFile = new File(pathToOutputPngFile);
    makeWhiteTransparent(pngFile, outputPngFile);
}

I even looked for open source libraries in addition to finding a bunch of responses here on SO but nothing seemed to work. 我甚至寻找开源库,除了在SO上找到一堆响应,但似乎没有任何效果。 That or the code was complex and unless you know what you're doing it was hard to understand (for example thresholds, etc.). 那个或代码很复杂,除非你知道你在做什么,否则很难理解(比如阈值等)。 I basically just want all #FFFFFF pixels in my PNG to be transparent. 我基本上只是希望我的PNG中的所有#FFFFFF像素都是透明的。

It should be as simple as setting the Alpha channel's value to 0, if the rest of the channels are at 255 它应该像将Alpha通道的值设置为0一样简单,如果其余通道为255

private static void makeWhiteTransparent(File in, File out)throws IOException{
    BufferedImage bi = ImageIO.read(in);
    int[] pixels = bi.getRGB(0, 0, bi.getWidth(), bi.getHeight(), null, 0, bi.getWidth());

    for(int i=0;i<pixels.length;i++){
        int color = pixels[i];
        int a = (color>>24)&255;
        int r = (color>>16)&255;
        int g = (color>>8)&255;
        int b = (color)&255;

        if(r == 255 && g == 255 && b == 255){
            a = 0;
        }

        pixels[i] = (a<<24) | (r<<16) | (g<<8) | (b);
    }

    BufferedImage biOut = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_ARGB);
    biOut.setRGB(0, 0, bi.getWidth(), bi.getHeight(), pixels, 0, bi.getWidth());
    ImageIO.write(biOut, "png", out);
}

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

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