image
Determine if an image has transparent pixels
In this tutorial we shall show you how to check if an Image has transparent pixels. This example shows the basic techniques in order to gain very detailed information about your images.
In short, to determine if an image has transparent pixels, one has to take the following steps:
- Load an image using
ImageIcon
andgetImage
method - If the Image is a
BufferedImage
the color model is already available, so you simply have to check the return value ofgetColorModel().hasAlpha()
methods. - If the Image is not buffered, you have to use a
PixelGrabber
to retrieve the image’s color model (grabbing a single pixel is usually sufficient) - Then use the
ColorModel
class to get the color model from thePixelGrabber
- And simply paint the buffered image in a new
Frame
Let’s see how the code looks like:
package com.javacodegeeks.snippets.desktop; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.PixelGrabber; public class ImageAlpha { public static void main(String[] args) { // Create frame with specific title boolean hasAlpha = false; // Get image - change to where your image file is located Image image = new ImageIcon("image.png").getImage(); // If buffered image, the color model is readily available if (image instanceof BufferedImage) { BufferedImage bimage = (BufferedImage) image; hasAlpha = bimage.getColorModel().hasAlpha(); } else { // 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) { System.out.println("Could not grab image pixels " + e.getMessage()); } // Get the image's color model ColorModel cm = pg.getColorModel(); hasAlpha = cm.hasAlpha(); } System.out.println("Has Alpha ? " + hasAlpha); } }
This was an example on how to determine if an image has transparent pixels.