Gets the transparency of an image. - Java 2D Graphics

Java examples for 2D Graphics:Image

Description

Gets the transparency of an image.

Demo Code


//package com.java2s;

import java.awt.Image;

import java.awt.Transparency;

import java.awt.image.BufferedImage;

import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;

public class Main {
    /**//from w  w  w.  ja  v a2  s . co  m
     * Gets the transparency of an image.
     *
     * @param image the image
     * @return OPAQUE, BITMASK or TRANSLUCENT (see java.awt.Transparency)
     */
    public static int getTransparency(Image image) {
        // If buffered image, the color model is readily available
        if (image instanceof BufferedImage) {
            BufferedImage bimage = (BufferedImage) image;
            return bimage.getColorModel().getTransparency();
        }
        // Use a pixel grabber to retrieve the image's color model;
        // grabbing a single pixel is usually sufficient
        PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
        }

        // Get the image's color model
        ColorModel cm = pg.getColorModel();

        int transparency = Transparency.OPAQUE;
        if (cm != null) {
            transparency = cm.getTransparency();
        }
        return transparency;
    }
}

Related Tutorials