Color Substitution

Color Substitution: Filtering an image can allow you to produce a number of interesting effects. Color substitution is one of the simplest effects. Basically what you do for color substitution is test the pixels for a file and change the ones which have a certain value to a different value. An explanation of how this is done appear below.
Step One: Import the java.awt.image.*; package. This will be necessary so you can use the PixelGrabber and MemoryImageSource classes.

Step Two: Declare some instances of the image class outside of the init method and then in the init method load one image and call a function to create the other(s) like this:

    c=getImage(getDocumentBase(), "cards/JS.gif");
    red=makeAlt(Color.red.getRGB());

Step Three: Here's the makeAlt function:
public Image makeAlt(int color){ Image temp=null; try{ int pixel[] = new int[w*h]; PixelGrabber pg = new PixelGrabber(c, 0, 0, w, h, pixel, 0, w); if(pg.grabPixels() &&((pg.status() & ImageObserver.ALLBITS) != 0)){ for(int x = 0; x< w * h; x++){ int r = (pixel[x] & 0x00ff0000)>>16; int g = (pixel[x] & 0x0000ff00)>>8; int b = (pixel[x] & 0x000000ff); if(r<100 && g<100 && b<100){ pixel[x]= color;; } } temp=createImage(new MemoryImageSource(w, h, pixel, 0, w)); } }catch(InterruptedException e) { } return temp; } First of all you will notice that it returns an Image and that it takes and integer value representing a color as a parameter. After declaring a variable called temp you encounter a try-catch block. The purpose of this block is to deal with any errors which might occur when the PixelGrabber methods are called. Elsewhere in your program values for w and h must be declared (they should be set to the dimensions of the image loaded into the variable called c). Before you can call the PixelGrabber constructor you must have an array of ints (called pixel in this example). The grabPixels method actually places all the values of the pixels in the int array. Once this is accomplished you are ready to start filtering.

The for loop iterates through all the pixel values stored in pixel and tests them one at a time. In this case we're looking for black pixels (or anything that's pretty dark -- with red, green, and blue values all less than 100). If we find such a pixel we will change it to the color value stored in the variable color. After that it's just a matter of creating an image and returning its value to the calling function.