Creating Images

Now that you know an image is just a grid of integers, it's not too difficult to create them. Of course you're not going to programmatically draw the Mona Lisa, but you might draw the Mandelbrot set or other pictures that can be created algorithmically.

There are a number of different ways to create an Image object from raw bytes. The easiest is with the java.awt.image.MemoryImageSource class. This class implements the java.awt.image.ImageProducer interface as will all classes that create images.

public MemoryImageSource(int width, int height, int[] pixels, int offset, int scan) 
public MemoryImageSource(int width, int height, ColorModel cm, byte[] pixels, 
 int offset, int scan) 
public MemoryImageSource(int width, int height, ColorModel cm, byte[] pixels, 
 int offset, int scan, Hashtable props) 
public MemoryImageSource(int width, int height, ColorModel cm, int[] pixels, 
 int offset, int scan) 
public MemoryImageSource(int width, int height, ColorModel cm, int[] pixels, 
 int offset, int scan, Hashtable properties) 

There are five different constructors in the MemoryImageSource class. for now let's concentrate on the first:

public MemoryImageSource(int width, int height, int[] pixels, int offset, int scan)

width is the width of the image in pixels. height is the height of the image in pixels. pixels is an int array that contains the actual image data. Each int in the array is a 32-bit quantity containing the RGB-transparency value for one pixel. offset is the index in the array where the image data starts. scan is the number of pixels in each line of the array. Most of the time this is the same as width.

To create an image you first fill an array with the data for the image, then use that array to construct a new MemoryImageSource. Then you pass the MemoryImageSource to the createImage() method of the Component class to actually produce an Image object.


Previous | Next | Top | Cafe au Lait

Copyright 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified July 21, 1999