get Compatible Buffered Image - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage

Description

get Compatible Buffered Image

Demo Code


import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import javax.imageio.ImageIO;

public class Main{
    public static final BufferedImage getCompatibleBufferedImage(Image img) {
        BufferedImage br_img;/*  ww  w  .  ja  v a  2  s  .co  m*/

        //checking if ALPHA component exists
        if (hasAlphaComponent(img)) {
            //creating comptable bufferedimage(ALPHA)...
            br_img = SystemConstants.GFX_DEFCONFIG.createCompatibleImage(
                    img.getWidth(null), img.getHeight(null),
                    Transparency.BITMASK);
        } else {
            //creating comptable bufferedimage(NON-ALPHA)...
            br_img = SystemConstants.GFX_DEFCONFIG.createCompatibleImage(
                    img.getWidth(null), img.getHeight(null),
                    Transparency.OPAQUE);
        }

        //now getting the graphics from the BufferedImage.
        Graphics2D g2d = (Graphics2D) br_img.getGraphics();

        //drawing onto bufferedimage
        g2d.drawImage(img, 0, 0, null);
        g2d.dispose();

        //return the bufferedimage containing our Image
        return br_img;
    }
    private static final boolean hasAlphaComponent(Image img) {
        // Use a pixel grabber to retrieve the image's color model;
        // grabbing a single pixel
        PixelGrabber pg = new PixelGrabber(img, 0, 0, 1, 1, false);
        try {
            //grabbed the pixel
            pg.grabPixels();

            //checking if has ALPHA component
            if (pg.getColorModel().hasAlpha())
                return true;
            else
                return false;
        } catch (InterruptedException e) {
            System.out
                    .println("Unable to retrieve APLHA information for Image ");
            return false;
        }

    }
}

Related Tutorials