net.jmge.gif

Class Gif89Encoder


public class Gif89Encoder
extends java.lang.Object

This is the central class of a JDK 1.1 compatible GIF encoder that, AFAIK, supports more features of the extended GIF spec than any other Java open source encoder. Some sections of the source are lifted or adapted from Jef Poskanzer's Acme GifEncoder (so please see the readme containing his notice), but much of it, including nearly all of the present class, is original code. My main motivation for writing a new encoder was to support animated GIFs, but the package also adds support for embedded textual comments.

There are still some limitations. For instance, animations are limited to a single global color table. But that is usually what you want anyway, so as to avoid irregularities on some displays. (So this is not really a limitation, but a "disciplinary feature" :) Another rather more serious restriction is that the total number of RGB colors in a given input-batch mustn't exceed 256. Obviously, there is an opening here for someone who would like to add a color-reducing preprocessor.

The encoder, though very usable in its present form, is at bottom only a partial implementation skewed toward my own particular needs. Hence a couple of caveats are in order. (1) During development it was in the back of my mind that an encoder object should be reusable - i.e., you should be able to make multiple calls to encode() on the same object, with or without intervening frame additions or changes to options. But I haven't reviewed the code with such usage in mind, much less tested it, so it's likely I overlooked something. (2) The encoder classes aren't thread safe, so use caution in a context where access is shared by multiple threads. (Better yet, finish the library and re-release it :)

There follow a couple of simple examples illustrating the most common way to use the encoder, i.e., to encode AWT Image objects created elsewhere in the program. Use of some of the most popular format options is also shown, though you will want to peruse the API for additional features.

Animated GIF Example

  import net.jmge.gif.Gif89Encoder;
  // ...
  void writeAnimatedGIF(Image[] still_images,
                        String annotation,
                        boolean looped,
                        double frames_per_second,
                        OutputStream out) throws IOException
  {
    Gif89Encoder gifenc = new Gif89Encoder();
    for (int i = 0; i <32still_images.length; ++i)
      gifenc.addFrame(still_images[i]);
    gifenc.setComments(annotation);
    gifenc.setLoopCount(looped ? 0 : 1);
    gifenc.setUniformDelay((int) Math.round(100 / frames_per_second));
    gifenc.encode(out);
  }
  
Static GIF Example
  import net.jmge.gif.Gif89Encoder;
  // ...
  void writeNormalGIF(Image img,
                      String annotation,
                      int transparent_index,  // pass -1 for none
                      boolean interlaced,
                      OutputStream out) throws IOException
  {
    Gif89Encoder gifenc = new Gif89Encoder(img);
    gifenc.setComments(annotation);
    gifenc.setTransparentIndex(transparent_index);
    gifenc.getFrameAt(0).setInterlaced(interlaced);
    gifenc.encode(out);
  }
  

See Also:
Gif89Frame, DirectGif89Frame, IndexGif89Frame

Constructor Summary

Gif89Encoder()
Use this default constructor if you'll be adding multiple frames constructed from RGB data (i.e., AWT Image objects or ARGB-pixel arrays).
Gif89Encoder(Color[] colors)
This constructor installs a user color table, overriding the detection of of a palette from ARBG pixels.
Gif89Encoder(Color[] colors, int width, int height, ci_pixels[] )
Convenience constructor for encoding a static GIF from index-model data.
Gif89Encoder(Image static_image)
Like the default except that it also adds a single frame, for conveniently encoding a static GIF from an image.

Method Summary

void
addFrame(Image image)
Convenience version of addFrame() that takes a Java Image, internally constructing the requisite DirectGif89Frame.
void
addFrame(int width, int height, ci_pixels[] )
The index-model convenience version of addFrame().
void
addFrame(Gif89Frame gf)
Add a Gif89Frame frame to the end of the internal sequence.
void
encode(OutputStream out)
After adding your frame(s) and setting your options, simply call this method to write the GIF to the passed stream.
Gif89Frame
getFrameAt(int index)
Get a reference back to a Gif89Frame object by position.
int
getFrameCount()
Get the number of frames that have been added so far.
void
insertFrame(int index, Gif89Frame gf)
Like addFrame() except that the frame is inserted at a specific point in the sequence rather than appended.
static void
main(String[] args)
A simple driver to test the installation and to demo usage.
void
setComments(String comments)
Specify some textual comments to be embedded in GIF.
void
setLogicalDisplay(Dimension dim, int background)
Sets attributes of the multi-image display area, if applicable.
void
setLoopCount(int count)
Set animation looping parameter, if applicable.
void
setTransparentIndex(int index)
Set the color table index for the transparent color, if any.
void
setUniformDelay(int interval)
A convenience method for setting the "animation speed".

Constructor Details

Gif89Encoder

public Gif89Encoder()
Use this default constructor if you'll be adding multiple frames constructed from RGB data (i.e., AWT Image objects or ARGB-pixel arrays).


Gif89Encoder

public Gif89Encoder(Color[] colors)
This constructor installs a user color table, overriding the detection of of a palette from ARBG pixels. Use of this constructor imposes a couple of restrictions: (1) Frame objects can't be of type DirectGif89Frame (2) Transparency, if desired, must be set explicitly.

Parameters:
colors - Array of color values; no more than 256 colors will be read, since that's the limit for a GIF.


Gif89Encoder

public Gif89Encoder(Color[] colors,
                    int width,
                    int height,
                    ci_pixels[] )
            throws IOException
Convenience constructor for encoding a static GIF from index-model data. Adds a single frame as specified.

Parameters:
colors - Array of color values; no more than 256 colors will be read, since that's the limit for a GIF.
width - Width of the GIF bitmap.
height - Height of same.


Gif89Encoder

public Gif89Encoder(Image static_image)
            throws IOException
Like the default except that it also adds a single frame, for conveniently encoding a static GIF from an image.

Parameters:
static_image - Any Image object that supports pixel-grabbing.

Method Details

addFrame

public void addFrame(Image image)
            throws IOException
Convenience version of addFrame() that takes a Java Image, internally constructing the requisite DirectGif89Frame.

Parameters:
image - Any Image object that supports pixel-grabbing.


addFrame

public void addFrame(int width,
                     int height,
                     ci_pixels[] )
            throws IOException
The index-model convenience version of addFrame().

Parameters:
width - Width of the GIF bitmap.
height - Height of same.


addFrame

public void addFrame(Gif89Frame gf)
            throws IOException
Add a Gif89Frame frame to the end of the internal sequence. Note that there are restrictions on the Gif89Frame type: if the encoder object was constructed with an explicit color table, an attempt to add a DirectGif89Frame will throw an exception.

Parameters:
gf - An externally constructed Gif89Frame.


encode

public void encode(OutputStream out)
            throws IOException
After adding your frame(s) and setting your options, simply call this method to write the GIF to the passed stream. Multiple calls are permissible if for some reason that is useful to your application. (The method simply encodes the current state of the object with no thought to previous calls.)

Parameters:
out - The stream you want the GIF written to.


getFrameAt

public Gif89Frame getFrameAt(int index)
Get a reference back to a Gif89Frame object by position.

Parameters:
index - Zero-based index of the frame in the sequence.

Returns:
Gif89Frame object at the specified position (or null if no such frame).


getFrameCount

public int getFrameCount()
Get the number of frames that have been added so far.

Returns:
Number of frame items.


insertFrame

public void insertFrame(int index,
                        Gif89Frame gf)
            throws IOException
Like addFrame() except that the frame is inserted at a specific point in the sequence rather than appended.

Parameters:
index - Zero-based index at which to insert frame.
gf - An externally constructed Gif89Frame.


main

public static void main(String[] args)
A simple driver to test the installation and to demo usage. Put the JAR on your classpath and run ala
java net.jmge.gif.Gif89Encoder {filename}
The filename must be either (1) a JPEG file with extension 'jpg', for conversion to a static GIF, or (2) a file containing a list of GIFs and/or JPEGs, one per line, to be combined into an animated GIF. The output will appear in the current directory as 'gif89out.gif'.

(N.B. This test program will abort if the input file(s) exceed(s) 256 total RGB colors, so in its present form it has no value as a generic JPEG to GIF converter. Also, when multiple files are input, you need to be wary of the total color count, regardless of file type.)

Parameters:
args - Command-line arguments, only the first of which is used, as mentioned above.


setComments

public void setComments(String comments)
Specify some textual comments to be embedded in GIF.

Parameters:
comments - String containing ASCII comments.


setLogicalDisplay

public void setLogicalDisplay(Dimension dim,
                              int background)
Sets attributes of the multi-image display area, if applicable.

Parameters:
dim - Width/height of display. (Default: largest detected frame size)
background - Color table index of background color. (Default: 0)

See Also:
Gif89Frame.setPosition(Point)


setLoopCount

public void setLoopCount(int count)
Set animation looping parameter, if applicable.

Parameters:
count - Number of times to play sequence. Special value of 0 specifies indefinite looping. (Default: 1)


setTransparentIndex

public void setTransparentIndex(int index)
Set the color table index for the transparent color, if any.

Parameters:
index - Index of the color that should be rendered as transparent, if any. A value of -1 turns off transparency. (Default: -1)


setUniformDelay

public void setUniformDelay(int interval)
A convenience method for setting the "animation speed". It simply sets the delay parameter for each frame in the sequence to the supplied value. Since this is actually frame-level rather than animation-level data, take care to add your frames before calling this method.

Parameters:
interval - Interframe interval in centiseconds.