我想知道如何在下面实现以下makeWhiteTransparent()
,以便它只需要一个文件,并且只在我现有的PNG中使白色像素透明。那只是完美的白色像素(#FFFFFF)。
public static void main(String[] args)
{
File pngFile = new File(pathToPngFile);
File outputPngFile = new File(pathToOutputPngFile);
makeWhiteTransparent(pngFile, outputPngFile);
}
我甚至寻找开源库,除了在SO上找到一堆响应,但似乎没有任何效果。那个或代码很复杂,除非你知道你在做什么,否则很难理解(比如阈值等)。我基本上只希望PNG中的所有#FFFFFF像素都是透明的。
答案 0 :(得分:2)
如果其余的通道都是255,那么它应该像将Alpha通道的值设置为0一样简单
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);
}