java背景透明

我有一个只包含彩色形状和透明背景的gif图像

我想用我想要的颜色替换形状的颜色(这个gif的颜色调色板只有2种颜色:在我的情况下是透明的和白色的).

我已经创建了一个过滤器,用红色正确替换白色(这是一个测试)

但是我遇到了我的方法imageToBufferedImage的问题,它删除了透明度并用黑色替换它(不知道为什么).

所以我到目前为止所做的是:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.File;
import javax.imageio.ImageIO;

public class TestPNG {

    public static void main(String[] args) throws Exception {

        File in = new File("bg.gif");
        BufferedImage source = ImageIO.read(in);
        int color = source.getRGB(0, 0);

        Image image = makeColorTransparent(source, new Color(color), new Color(255, 0, 0));

        BufferedImage transparent = imageToBufferedImage(image);

        File out = new File("bg2.gif");
        ImageIO.write(transparent, "gif", out);

    }

    private static BufferedImage imageToBufferedImage(Image image) {
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = bufferedImage.createGraphics();
        //g2.setBackground(Color.blue);
        g2.clearRect(0, 0, 200, 40);
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        return bufferedImage;
    }

    public static Image makeColorTransparent(BufferedImage im, final Color search, final Color replace) {
        ImageFilter filter = new RGBImageFilter() {
                public final int filterRGB(int x, int y, int rgb) {
                        if (rgb == search.getRGB()) {
                            return replace.getRGB();
                        } else {
                            return rgb;
                        }
                }
        };
        ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
        return Toolkit.getDefaultToolkit().createImage(ip);
    }

}

最佳答案 您的代码中有3个问题:

1)更换

Image image = makeColorTransparent(source, new Color(color), new Color(255, 0, 0));

Image image = makeColorTransparent(source, color, new Color(255, 0, 0));

public static Image makeColorTransparent(BufferedImage im, final Color search, final Color replace) {
...
if (rgb == search.getRGB()) {
...
}

public static Image makeColorTransparent(BufferedImage im, final int search, final Color replace) {
...
if (rgb == search) {
...
}

由于某种原因,由于某种原因,source.getRGB(0,0)忽略alpha值并变为白色((255,255,255,0)变为(255,255,255,255))

2)你不能使用int color = source.getRGB(0,0),因为它使用第一个像素的颜色(透明).您应该使用其他一些代码(比如在控制台中询问颜色)来找出以int颜色存储的像素颜色

3)您正在使用Color.BLACK(默认)清除imageToBufferedImage(…)中BufferedImage bufferedImage的颜色.替换//g2.setBackground(Color.blue);使用g2.setBackground(new Color(0,0,0,0));或删除g2.clearRect(…);

点赞