make BufferedImage Color Transparent - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Color

Description

make BufferedImage Color Transparent

Demo Code


//package com.java2s;

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;

public class Main {
    public static BufferedImage makeColorTransparent(BufferedImage im,
            final Color color) {
        ImageFilter filter = new RGBImageFilter() {
            public int markerRGB = color.getRGB() | 0xFFFF0000;

            public final int filterRGB(int x, int y, int rgb) {
                if ((rgb | 0xFF000000) == markerRGB) {
                    return 0x00FFFFFF & rgb;
                } else {
                    return rgb;
                }/*  ww w. j av  a2s. co  m*/
            }
        };
        ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
        return getBI(Toolkit.getDefaultToolkit().createImage(ip));
    }

    private static BufferedImage getBI(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;

    }
}

Related Tutorials