[英]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.