如何在BufferedImage中使颜色透明并保存为PNG

时间:2009-03-20 09:03:55

标签: java image colors png transparent

我一直在网上搜索这个,但我没有找到任何体面的帮助。

我有一个BufferedImage,我已经用ImageIO读过了。现在我想将该图像中的某种颜色设置为透明,并将图像保存为PNG。

我知道我不能仅仅因为显而易见的原因而“涂抹”透明色,所以我猜我需要某种过滤器。

有人为此获得了一些示例代码吗?

2 个答案:

答案 0 :(得分:40)

我最近这样做,回答了我的项目经理的问题 将灰色转换为透明度的函数是:

  private Image TransformGrayToTransparency(BufferedImage image)
  {
    ImageFilter filter = new RGBImageFilter()
    {
      public final int filterRGB(int x, int y, int rgb)
      {
        return (rgb << 8) & 0xFF000000;
      }
    };

    ImageProducer ip = new FilteredImageSource(image.getSource(), filter);
    return Toolkit.getDefaultToolkit().createImage(ip);
  }

实际上,它作用于灰度图像,所以我只是将RGB组件(R一个)复制到alpha,丢弃其他在我的情况下相同的组件。
您可以对其进行调整以过滤特定颜色,例如。测试平等或范围等。
当然,BufferedImage必须是BufferedImage.TYPE_INT_ARGB类型。

我没有解决保存问题,因为它非常简单,但我也可以添加此代码页。

[编辑]将图像转换为BufferedImage:

BufferedImage dest = new BufferedImage(
    imageWidth, imageHeight,
    BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();

[编辑2]我是在Christoffer发布他的完整解决方案之后来的,但这是我的,我展示了如何使一系列颜色透明。可以改进,例如。改为使用HSB组件。

import java.awt.*;
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.*;

import javax.imageio.ImageIO;

public class AddTransparency
{
  AddTransparency() throws IOException
  {
    String imagePath = "E:/Documents/images/";
    File inFile = new File(imagePath, "map.png");
    BufferedImage image = ImageIO.read(inFile);

    Image transpImg1 = TransformGrayToTransparency(image);
    BufferedImage resultImage1 = ImageToBufferedImage(transpImg1, image.getWidth(), image.getHeight());

    File outFile1 = new File(imagePath, "map_with_transparency1.png");
    ImageIO.write(resultImage1, "PNG", outFile1);

    Image transpImg2 = TransformColorToTransparency(image, new Color(0, 50, 77), new Color(200, 200, 255));
    BufferedImage resultImage2 = ImageToBufferedImage(transpImg2, image.getWidth(), image.getHeight());

    File outFile2 = new File(imagePath, "map_with_transparency2.png");
    ImageIO.write(resultImage2, "PNG", outFile2);
  }

  private Image TransformGrayToTransparency(BufferedImage image)
  {
    ImageFilter filter = new RGBImageFilter()
    {
      public final int filterRGB(int x, int y, int rgb)
      {
        return (rgb << 8) & 0xFF000000;
      }
    };

    ImageProducer ip = new FilteredImageSource(image.getSource(), filter);
      return Toolkit.getDefaultToolkit().createImage(ip);
  }

  private Image TransformColorToTransparency(BufferedImage image, Color c1, Color c2)
  {
    // Primitive test, just an example
    final int r1 = c1.getRed();
    final int g1 = c1.getGreen();
    final int b1 = c1.getBlue();
    final int r2 = c2.getRed();
    final int g2 = c2.getGreen();
    final int b2 = c2.getBlue();
    ImageFilter filter = new RGBImageFilter()
    {
      public final int filterRGB(int x, int y, int rgb)
      {
        int r = (rgb & 0xFF0000) >> 16;
        int g = (rgb & 0xFF00) >> 8;
        int b = rgb & 0xFF;
        if (r >= r1 && r <= r2 &&
            g >= g1 && g <= g2 &&
            b >= b1 && b <= b2)
        {
          // Set fully transparent but keep color
          return rgb & 0xFFFFFF;
        }
        return rgb;
      }
    };

    ImageProducer ip = new FilteredImageSource(image.getSource(), filter);
      return Toolkit.getDefaultToolkit().createImage(ip);
  }

  private BufferedImage ImageToBufferedImage(Image image, int width, int height)
  {
    BufferedImage dest = new BufferedImage(
        width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = dest.createGraphics();
    g2.drawImage(image, 0, 0, null);
    g2.dispose();
    return dest;
  }

  public static void main(String[] args) throws IOException
  {
    AddTransparency at = new AddTransparency();
  }
}

答案 1 :(得分:16)

感谢PhilLo,这是我的演示应用程序的完整解决方案。

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

        File in = new File("C:\\Users\\Christoffer\\Desktop\\christoffer.jpg");
        BufferedImage source = ImageIO.read(in);

        int color = source.getRGB(0, 0);

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

        BufferedImage transparent = imageToBufferedImage(image);

        File out = new File("C:\\Users\\Christoffer\\Desktop\\trans.PNG");
        ImageIO.write(transparent, "PNG", 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.drawImage(image, 0, 0, null);
        g2.dispose();

        return bufferedImage;

    }

    public static Image makeColorTransparent(BufferedImage im, final Color color) {
        ImageFilter filter = new RGBImageFilter() {

            // the color we are looking for... Alpha bits are set to opaque
            public int markerRGB = color.getRGB() | 0xFF000000;

            public final int filterRGB(int x, int y, int rgb) {
                if ((rgb | 0xFF000000) == markerRGB) {
                    // Mark the alpha bits as zero - transparent
                    return 0x00FFFFFF & rgb;
                } else {
                    // nothing to do
                    return rgb;
                }
            }
        };

        ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
        return Toolkit.getDefaultToolkit().createImage(ip);
    }