An Example of Creating Images

Let's suppose you want a 100 pixel wide, 50 pixel high image that's pure purple. A very nice purple shade is composed of 217 red, 10 green, 186 blue. (I used Adobe Photoshop to get these numbers, but there are many other ways.)

The integer value of this purple is formed like this:

int red = 217;
int green = 10;
int blue = 186;
int opaque = 255;
int purple = (opaque << 24 ) | (red << 16 ) | (green << 8 ) | blue;

The image we want is 100 pixels wide by 50 pixels high so the array has to have 100 * 50 = 5000 elements. Thus,

   int[] pixels = new int[5000];

Next, you fill the array with the purple value. A simple for loop suffices:

   for (int i=0; i < pixels.length; i++) pixels[i] = purple;

Now that the array is created you can create the MemoryImageSource.

 MemoryImageSource purpleMIS = new MemoryImageSource(100, 50, pixels, 0, 50);

Assuming you're inside an applet or other subclass of java.awt.Component, you can do the following. If you're not, you'll need to prefix the call to createImage() with a reference variable.

   Image purplebox = createImage(purpleMIS);

You can now draw this image just like one you loaded from the network with getImage().

You can use one ImageProducer to create multiple images, and you can use one array of pixels to create multiple MemoryImageSources. However, if you do this you should not change the array after it's initially created.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 2005 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified April 20, 2005