Tag Archives: Image

Testing if an image has transparant pixels.


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:

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 = 
        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 {
    } catch (InterruptedException e) {

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


Filtering the Red, Green or Black colors from an Image



// This filter removes all but the red values in
// an image
class GetRedFilter extends RGBImageFilter {
    public GetRedFilter() {
        // When this is set to true, the filter
        // will work with images
        // whose pixels are indices into a color
        // table (IndexColorModel).
        // In such a case, the color values in
        // the color table are filtered.
        canFilterIndexColorModel = true;

    // This method is called for every pixel in
    // the image
    public int filterRGB(int x, int y, int rgb) {
        if (x == -1) {
            // The pixel value is from the image's color table rather than the image itself
        // Return only the red component
        return rgb & 0xffff0000;