Testing if an image has transparant pixels.

Introduction

If you use sprites with transparency in your game — and you most likely do for the UI at least — you’ll probably want to pay attention to the fully transparent pixels of your textures (or should I say “texels”).

Even with an alpha of 0, a pixel still has some RGB color value associated with it. That color shouldn’t matter, right? After all if the pixel is completely transparent, who cares about its color…

Well this color does actually matter, getting it wrong leads to artifacts which are present in many games out there. Most of the time the corruption is very subtle and you won’t notice it but in some cases it’s really standing out.

The example below shows how you can test if your image contains transparant pixels. The Image’s ColorModel class has a method hasAlpha() which returns true if the Image has transparant pixels.This example shows two ways to obtain the ColorModel:

public static boolean hasAlpha(Image image) {
    // If the image is a buffered image, 
    // the ColorModel is alreadily available
    // if not we have to get retrieve it. 
    if (image instanceof BufferedImage)
        BufferedImage bimage = 
        (BufferedImage)image;
        return bimage.getColorModel().hasAlpha();
    }

    // Use a pixel grabber to retrieve the
    // image's ColorModel;
    // 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();
    return cm.hasAlpha();
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.