Gif4J Library :: Tutorial
Gif4J Library v 1.0 Tutorial

CONTENT
Constructing a gif image, Resize Strategies & Looping
Constructing gif frames and adding them to gif image
Encoding (writing gif images to output stream) & ImageIO integration
Constructing watermarks and applying them to gif frames
Morphing Filters
Text Rendering
 Constructing a gif image, Resize Strategies & Looping

Class:GifImage

Constructors & Resize Strategies

GifImage class has the next constructors:

    public GifImage();
    public GifImage(int resizeStrategy);
    public GifImage(int width, int height);
    public GifImage(int width, int height, int resizeStrategy);

The first two constructors create GifImage with indefinite general gif image width and height - these parameters will be taken from the first added frame.

Hint: You can always get the current gif image width/height using the next methods:

    public int getCurrentLogicWidth()
    public int getCurrentLogicHeight()

Resize Strategy parameter can be one of the predefined resize strategies: crop to fit image size, scale to fit image size and extend to current. First two strategies let to fix the general gif image size (logical screen size). The last extends logical screen size to fit all added gif frames.
Below examples demostrate all strategies (see examples/ResizeStrategies):


crop to fit image size (predefined size: 150x150)


scale to fit image size (predefined size: 150x150)


extend to current (extended size: 200x200)

Looping

Animated gif images can have an Application Extension Block that tells Encoder to loop the entire GIF file. Based on the Gif89a specification you can set number of iterations between 0 and 65535 where 0 means indefinite looping. The next method should be used:

    public void setLoopNumber(int number

Note: A lot of gif encoders and viewers (including Microsoft IE browser) ignore this parameter and iterate animated gif image indefinitely. You can emulate a loop with only one iteration by setting the long delay time for the last frame.
Hint: You can set default delay time between frames. This delay is automatically applied to adding frames without delay parameter set. The next method should be used:

    public void setDefaultDelay(int delay

Note: Any delay parameter is set in 1/100 (centiseconds) - value 100 means delay in 1 second. Default delay between frames is set to 200 (2 seconds).

[CONTENT]

 Constructing gif frames and adding them to gif image

Class:GifFrame

Constructing & Positioning

GifFrame class constructors can be divided into 2 types according to the desired frame position (absolute or relative). "absolute positioning" costructors contain Point parameter and "relative positioning" constructors contain layout constraint parameter.
Note: If you use "relative positioning" then the final position is calculated according to one of the predifined layout constraint before the final encoding process starts.
Below examples demostrate relative positioning and how you can use it (see examples/FramePositioning):


(size: 300x300, every frame size: 100x100)


(size: 200x200, every frame size: 100x100)


image tour (size: 300x240, every frame is scaled down using ImageUtils to 150x130)

Disposal Methods & Delay Time

Disposal Method - indicates the way in which the graphic is to be treated after being displayed. According to Gif89a format specification there are 4 disposal methods: "not specified", "do not dispose", "restore to background color" and "restore to previous" (see API for more information).
You can set disposal method through corresponding GifFrame constructors or using the next method:

    public void setDisposalMethod(int disposalMethod

Delay Time - If not 0, this field specifies the number of hundredths (1/100) of a second to wait before continuing with the processing of the Data Stream. The clock starts ticking immediately after the graphic is rendered. You can set delay time through corresponding GifFrame constructors or using the next method:

    public void setDelay(int delay

Adding gif frames to gif image

To add GifFrame(s) to GifImage(s) you can use the next methods:

    public GifImage addGifFrame(GifFrame frame
    public GifImage addGifFrame(GifFrame frame, MorphingFilter filter
    public GifImage addGifFrame(GifFrame frame, Watermark watermark
    public GifImage addGifFrame(GifFrame frame, MorphingFilter filter, Watermark watermark

See javadoc GifFrame API for more information.

[CONTENT]

 Encoding (writing gif images to output stream) & ImageIO integration

Class:GifEncoder

Encoding using GifEncoder class

GifEncoder class has the next encoding static methods:

  public static final void encode
          (GifImage gifImage, OutputStream outputStream); 

  public static final void encode
          (GifImage gifImage,
          OutputStream outputStream, 

          boolean forceGlobalColorTableUsage); 

  public static final void encode
          (BufferedImage image, OutputStream outputStream); 

  public static final void encode
          (BufferedImage image, DataOutput dataOutput); 

The last two methods can be used to encode BufferedImage(s) directly to noneanimated (consists of one frame) gif image files. If the specified BufferedImage contains more than 256 unique colors then it'll be automatically quantized using the Gif4J Quantizer class.
Parameter forceGlobalColorTableUsage forces Global Color Table use. If this parameter is set to true then Local Color Tables from all frames will be union to one Global Color Table. It's useful to optimize final image size (every Local Color Table takes up to 768 bytes). Especially this option is recommended to set for encoding gif images with a lot of internal frames (for example, after applying Morphing Filters).

ImageIO integration

You can find more infomation about The Java Image I/O API here. Just one quotation: "The Java Image I/O API provides a pluggable architecture for working with images stored in files and accessed across the network. It offers substantially more flexibility and power than the previously available APIs for loading and saving images." To enable ImageIO support by the Gif4J library you just need to add library jar file to the CLASSPATH. The Java Image I/O API should automatically resolve the Gif4J library as a plug-in, load the Gif4J service provider classes, and registers the Gif4J service provider instance.
The next code checks that the Gif4J library has been resolved correctly:

    Iterator iterator = ImageIO.getImageWritersByFormatName("gif");
    while (iterator.hasNext()) {
       ImageWriter imageWriter = (ImageWriteriterator.next();
        ImageWriterSpi spi = imageWriter.getOriginatingProvider();
        System.out.println("Vendor: "+spi.getVendorName());
        System.out.println("Format description: "
                + imageWriter.getOriginatingProvider().getDescription(null)+"\n");
    }

The output should contain something like this:

Vendor: Gif4J Software, http://www.gif4j.com/
Format description: GRAPHICS INTERCHANGE FORMAT(sm) Version 89a


If nothing has been found then you should call ImageIO.scanForPlugins() method to force the ImageIO scans the application class path for plug-ins.
If the Gif4J service provider has been detected and loaded then an image Writing in the gif format is equally simple:

        BufferedImage bi = null;
// skip bi initialization
        try {
            File f = new File("c:\\images\\myimage.gif");
            ImageIO.write(bi, "gif", f);
        catch (IOException e) {
        }

Examples

Please review the examples/ImageIO example.

[CONTENT]

 Constructing watermarks and applying them to gif frames

Class:Watermark

Constructing & Positioning

This class is used to prepare and apply (paint with the specified transparency) images as watermarks to GifFrame(s). Absolute and relative (layout constraint based) positioning are supported.
Watermark class constructors can be divided into 2 types according to the desired position type (absolute or relative). "absolute positioning" costructors contain Point parameter and "relative positioning" constructors contain layout constraint parameter.
Also you can specify watermark's transparency parameter which is represented by float value between 0 (absolutely transparent) and 1 (absolutely opaque). Default is 0.5f. Below examples demostrate positioning and transparency opportunities (see examples/Watermarks and examples/ImageTour1):


(size: 150x150, 5 frames - each with different relative position and the last with "cover consecutively" watermark)


(size: 160x120, image tour - the real example that demostrates how you can use watermarks)



To apply watermark(s) to the specified frame you should add this frame to a gif image using the next methods:

    public GifImage addGifFrame(GifFrame frame, Watermark watermark
    public GifImage addGifFrame(GifFrame frame, MorphingFilter filter, Watermark watermark

Hint: You can separately use Watermark class capability to render watermarks on BufferedImage(s) using the  public BufferedImage apply(BufferedImage image method.

[CONTENT]

 Morphing Filters

Base Class: MorphingFilter
Filters: CellFilter, CurtainFilter, MillFilter, MozaicFilter, RadarFilter, SnakeFilter, TunnelFilter

Morphing filters are the unique feature of the Gif4J library which lets you to create an amazing gif animation without any additional coding. There are 7 base morphing filters with more than 20 morphing options. To apply the specified filter to a gif frame you just need to create an instance (or use already created - you can apply one filter's instance to any number of gif frames) of the selected filter (see filters API for more information) and add the GifFrame to the GifImage using one of the next methods:

    public GifImage addGifFrame(GifFrame frame, MorphingFilter filter
    public GifImage addGifFrame(GifFrame frame, MorphingFilter filter, Watermark watermark

Below examples demostrate morphing filters in action (see examples/MorphingFilters and examples/MorphingImageTours):


(CellFilter)

(CurtainFilter)

(MillFilter)

(RadarFilter)

(MozaicFilter)

(TunnelFilter)

(SnakeFilter)


(Cell and Curtain filters have been used)


(Mill, Mozaic and Tunnel filters have been used)


(Snake filter with different options has been used)

Note: For every filter you can specify 'delay time between frames' parameter (in 1/100 seconds). Default delay is equal to 10. To do an animation smoother please specify this parameter small but note that some gif viewers and browsers (including Microsoft IE) can ignore very small delay between frames. Experience has shown that, for example, Microsoft Internet Explorer ignores delay between frames less than 6 and in this case uses own default delay. So if you want to get the fastest gif animation then set the delay to 6.
Note: Morphing filtering is based on fragmentation one gif frame to several and it increases the total number of gif frames greatly. As you know by default every output gif frame has own local color table which can take up to 768 bytes in the result file. To prevent this process encode the GifImage with "force global color table usage" option (see GifEncoder class API for more information).

[CONTENT]

 Text Rendering

Class:TextPainter

This class is intended for drawing the text across the single or multiple lines on the BufferedImage(s). It can be very convenient for adding some text information to images, creation text-based watermarks etc. TextPainter class in its basis uses Java 2D lays and supports some Java 2D API concepts such as Paint etc. This class actually represents a small superstructure above Java2D and uses only a small part of Java2D functionality.
TextPainter context contains the next attributes: font (instance of java.awt.Font), foreground paint (instance of java.awt.Color, java.awt.GradientPaint or java.awt.TexturePaint), backgroung color (instance of java.awt.Color), outline paint (instance of java.awt.Color, java.awt.GradientPaint or java.awt.TexturePaint) and antialiasing (on/off).
You can get and set these attributes using the constructors and suite of getter/setter methods. There are 2 main rendering methods:

  public BufferedImage renderString(String str) ;
  public BufferedImage renderText(String text, int width, boolean outline, boolean centralized) ;


The first method renders single string using the specified attributes from the TextPainter context. Size of the returned BufferedImage object is equal to visual bounds of the specified string to render.
The second method renders line-wraped to the specified width text using the specified attributes from the TextPainter context. Width of the returned BufferedImage object is equal to the specified width. Height is automatically extended to contain all text lines. Below examples demostrate some TextPainter features (see examples/TextRendering, examples/TextBanner, examples/ProductIcon1 and examples/ProductIcon2):
















Hint: To render outlined text with better quality use BOLD font instances.

Hint: It is no secret that any published on a site text information are not protected and can be easily grabbed by special scripts or even by copy/paste. You can prevent the grabbing of any privacy information (passwords, e-mails, price lists, financial reports etc.) by publishing such information as a gif images. With the help of Gif4J Library such functionality can be added easily for short time.

Note: Sometimes you can get ugly rendered text on the other platform while on your own platform text is rendered well. Such problems are usually connected with failing one or another font. You can get all supported fonts on the exact platform by calling getAllFonts() method of the GraphicsEnvironment class:

        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        Font[] allfonts = ge.getAllFonts();

[CONTENT]

Gif4J Library (Copyright © 2004 Gif4J Software)