繁体   English   中英

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

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

我想知道如何在下面实现下面的makeWhiteTransparent() ,以便它获取一个文件,并且只在我现有的PNG makeWhiteTransparent()白色像素透明。 那只是完美的白色像素(#FFFFFF)。

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

我甚至寻找开源库,除了在SO上找到一堆响应,但似乎没有任何效果。 那个或代码很复杂,除非你知道你在做什么,否则很难理解(比如阈值等)。 我基本上只是希望我的PNG中的所有#FFFFFF像素都是透明的。

它应该像将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