Real'sHowTo AddThis Feed Button
Custom Search

Make a color transparentTag(s): AWT


Here we have an Image with a blue background like and we want to display it in an Applet with a white background. All we have to do is to look for the blue color with the "Alpha bits" set to opaque and make them transparent.

[Transparency.java]
import java.awt.*;
import java.awt.image.*;

public class Transparency {
  public static Image makeColorTransparent
    (Image im, final Color color) {
    ImageFilter filter = new RGBImageFilter() {
      // the color we are looking for... Alpha bits are set to opaque
      public int markerRGB = color.getRGB() | 0xFF000000;

      public final int filterRGB(int x, int y, int rgb) {
        if ( ( rgb | 0xFF000000 ) == markerRGB ) {
          // Mark the alpha bits as zero - transparent
          return 0x00FFFFFF & rgb;
          }
        else {
          // nothing to do
          return rgb;
          }
        }
      }; 

    ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
    return Toolkit.getDefaultToolkit().createImage(ip);
    }
}
[app.java]
import java.awt.image.*;
import java.awt.*;
import java.net.*;

public class app extends java.applet.Applet {
  Image GifOriginalWithWithBlueBackground;
  Image GifModifiedWithTransparentBackground;

  public void init() {
    setBackground(new Color(0).white);  
  
    MediaTracker media = new MediaTracker(this);
    // image of our friend, Gumby with a blue background
    GifOriginalWithWithBlueBackground = 
       getImage(getDocumentBase(),"gumbyblu.gif");
    media.addImage(GifOriginalWithWithBlueBackground,0);
    try {
      media.waitForID(0);
      GifModifiedWithTransparentBackground = 
       Transparency.makeColorTransparent
        (GifOriginalWithWithBlueBackground, new Color(0).blue);
      } 
    catch(InterruptedException e) {}
    }

  public void paint(Graphics g) {
    g.drawImage(GifOriginalWithWithBlueBackground, 10,10,this);
    g.drawImage(GifModifiedWithTransparentBackground,10, 80,this);
    }
}
[x.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="app.class"  
        NAME="myApplet" 
        HEIGHT=200 WIDTH=200>
</APPLET>
</BODY></HTML>

blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]