Getting the Transparent Pixel and Number of Colors Used in a GIF Image - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Color

Description

Getting the Transparent Pixel and Number of Colors Used in a GIF Image

Demo Code


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.PixelGrabber;

import javax.swing.ImageIcon;

public class Main {
  public void main(String[] argv) {
    Image image = new ImageIcon("image.gif").getImage();

    IndexColorModel colorModel = (IndexColorModel) getColorModel(image);

    int trans = colorModel.getTransparentPixel();
    if (trans == -1) {
      // There is no transparent pixel
    }/*w ww  . j a va 2 s . c o  m*/

    // Get the number of colors
    int numColors = colorModel.getMapSize();
  }

  public static ColorModel getColorModel(Image image) {
    if (image instanceof BufferedImage) {
      BufferedImage bimage = (BufferedImage) image;
      return bimage.getColorModel();
    }
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
      pg.grabPixels();
    } catch (InterruptedException e) {
    }
    ColorModel cm = pg.getColorModel();
    return cm;
  }
}

Related Tutorials