Java BufferedImage to Transparent getTransparentImage(BufferedImage i)

Here you can find the source of getTransparentImage(BufferedImage i)

Description

get Transparent Image

License

Open Source License

Declaration

public static BufferedImage getTransparentImage(BufferedImage i) 

Method Source Code

//package com.java2s;
/*/*from   ww w  . ja  v a2 s .co  m*/
 * Copyright (C) 2007, 2008 Quadduc <quadduc@gmail.com>
 * Copyright (C) 2007, 2011 IsmAvatar <IsmAvatar@gmail.com>
 * Copyright (C) 2007 Clam <clamisgood@gmail.com>
 * Copyright (C) 2013, 2014 Robert B. Colton
 *
 * This file is part of LateralGM.
 * LateralGM is free software and comes with ABSOLUTELY NO WARRANTY.
 * See LICENSE for details.
 */

import java.awt.Graphics;

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 javax.swing.ImageIcon;

public class Main {
    public static BufferedImage getTransparentImage(BufferedImage i) {
        if (i == null)
            return null;
        final int t = i.getRGB(0, i.getHeight() - 1) & 0x00FFFFFF;
        ImageFilter filter = new RGBImageFilter() {
            @Override
            public int filterRGB(int x, int y, int rgb) {
                if ((rgb & 0x00FFFFFF) == t)
                    return t;
                return rgb;
            }
        };
        ImageProducer ip = new FilteredImageSource(i.getSource(), filter);
        return toBufferedImage(Toolkit.getDefaultToolkit().createImage(ip));
    }

    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage)
            return (BufferedImage) image;

        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();

        BufferedImage bimage = new BufferedImage(image.getWidth(null), image.getHeight(null),
                BufferedImage.TYPE_INT_ARGB);
        Graphics g = bimage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }
}

Related

  1. getTransperentImage(BufferedImage origImage, BufferedImage compImg)
  2. makeColorTransparent(BufferedImage im, final Color color)
  3. makeColorTransparent(BufferedImage im, final Color color)
  4. makeColorTransparent(BufferedImage image, Color color)