GIFEncoder sample code. This code uses PixelGrabber to construct a GIF image.
/**
*
*
* @(#)GIFEncoder.java 0.90 4/21/96 Adam Doppelt
*
* GIFEncoder is based upon gifsave.c, which was written and released
* by:
*
* Sverre H. Huseby
* Bjoelsengt. 17
* N-0468 Oslo
* Norway
*
* Phone: +47 2 230539
* sverrehu [at] ifi.uio.no
*/
/** ******************************************************
*
* GIFEncoder
*
*/
public GIFEncoder(Image image) throws AWTException {
width_ = (short)image.getWidth(null);
height_ = (short)image.getHeight(null);
int values[] = new int[width_ * height_];
/** "Attach" pixelgrabber to the image */
PixelGrabber grabber = new PixelGrabber(
image, 0, 0, width_, height_, values, 0, width_);
/** Retrieve int values for the pixels of the image */
try {
if(grabber.grabPixels() != true)
throw new AWTException("Grabber returned false: " +
grabber.status());
}
catch (InterruptedException e) {}
/** Need 3 2-d Arrays to store RGB byte value for each pixel */
/** NOTE: Each array is the size of the original image */
byte r[][] = new byte[width_][height_];
byte g[][] = new byte[width_][height_];
byte b[][] = new byte[width_][height_];
int index = 0;
/** Bit shift the integer values to get the RGB values */
for (int y = 0; y < height_; ++y) {
for (int x = 0; x < width_; ++x) {
r[x][y] = (byte)((values[index] >> 16) & 0xFF);
g[x][y] = (byte)((values[index] >> 8) & 0xFF);
b[x][y] = (byte)((values[index]) & 0xFF);
++index;
}
}
/** Generate 256 color LUT for GIF */
ToIndexedColor(r, g, b);
}
/** ******************************************************
*
* ToIndexedColor
*
*/
void ToIndexedColor(byte r[][], byte g[][],
byte b[][]) throws AWTException {
pixels_ = new byte[width_ * height_];
/** Array for 256 color RGB byte values */
colors_ = new byte[256 * 3];
int colornum = 0;
/** Iterate over 3 2-D RGB byte arrays */
for (int x = 0; x < width_; ++x) {
for (int y = 0; y < height_; ++y) {
int search;
for (search = 0; search < colornum; ++search)
if (colors_[search * 3] == r[x][y] &&
colors_[search * 3 + 1] == g[x][y] &&
colors_[search * 3 + 2] == b[x][y])
break;
if (search > 255)
throw new AWTException("Too many colors.");
pixels_[y * width_ + x] = (byte)search;
if (search == colornum) {
colors_[search * 3] = r[x][y];
colors_[search * 3 + 1] = g[x][y];
colors_[search * 3 + 2] = b[x][y];
++colornum;
}
}
}
/** BitsNeeded is the number of bits required to specify
a unique index in the LUT. Eg: If the LUT has 4 colors this
value is 2 */
numColors_ = 1 << BitUtils.BitsNeeded(colornum);
byte copy[] = new byte[numColors_ * 3];
System.arraycopy(colors_, 0, copy, 0, numColors_ * 3);
colors_ = copy;
}