简体   繁体   中英

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. That is ONLY the perfectly white pixels (#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. 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.

It should be as simple as setting the Alpha channel's value to 0, if the rest of the channels are at 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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