Creating GIF image from normal images in Java

I wanted to create a Facebook app in which user’s best 10 pics would be converted into a GIF image and uploaded to his profile. So after googling a lot I found some useful class which converts group of images into a GIF image.

GifSequenceWriter is the class which I found. It has been attached at the end

Here is the code which uses GifSequenceWriter to create a GIF image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ImageOutputStream output = new FileImageOutputStream(new File(OUTPUT_PATH + ".gif"));
 
int timeBetweenFramesMS = 1000;
 
boolean loopContinuously = true;
 
int imgType = 0;
 
GifSequenceWriter writer = new GifSequenceWriter(output, imgType,
						timeBetweenFramesMS, loopContinuously);
BufferedImage img1 = null;//create buffered image
writer.writeToSequence(img1);
 
BufferedImage img2 = null;//create buffered image
writer.writeToSequence(img2);
 
writer.close();

output is the path where you want to save final GIF image
timeBetweenFramesMS is the delay in milliseconds between each image
loopContinuously should GIF run in a loop or stop once it is complete

We pass these parameters to GifSequenceWriter constructor and create a writer object
Next we need to create BufferedImage images and keep on adding to the writer which we just created. In the end we obviously need to close the writer

Here is the GifSequenceWriter class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
 
import javax.imageio.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.image.*;
import java.io.*;
import java.util.Iterator;
 
public class GifSequenceWriter {
  protected ImageWriter gifWriter;
  protected ImageWriteParam imageWriteParam;
  protected IIOMetadata imageMetaData;
 
  /**
   * Creates a new GifSequenceWriter
   * 
   * @param outputStream the ImageOutputStream to be written to
   * @param imageType one of the imageTypes specified in BufferedImage
   * @param timeBetweenFramesMS the time between frames in miliseconds
   * @param loopContinuously wether the gif should loop repeatedly
   * @throws IIOException if no gif ImageWriters are found
   *
   * @author Elliot Kroo (elliot[at]kroo[dot]net)
   */
  public GifSequenceWriter(
      ImageOutputStream outputStream,
      int imageType,
      int timeBetweenFramesMS,
      boolean loopContinuously) throws IIOException, IOException {
    // my method to create a writer
    gifWriter = getWriter(); 
    imageWriteParam = gifWriter.getDefaultWriteParam();
    ImageTypeSpecifier imageTypeSpecifier =
      ImageTypeSpecifier.createFromBufferedImageType(imageType);
 
    imageMetaData =
      gifWriter.getDefaultImageMetadata(imageTypeSpecifier,
      imageWriteParam);
 
    String metaFormatName = imageMetaData.getNativeMetadataFormatName();
 
    IIOMetadataNode root = (IIOMetadataNode)
      imageMetaData.getAsTree(metaFormatName);
 
    IIOMetadataNode graphicsControlExtensionNode = getNode(
      root,
      "GraphicControlExtension");
 
    graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
    graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
    graphicsControlExtensionNode.setAttribute(
      "transparentColorFlag",
      "FALSE");
    graphicsControlExtensionNode.setAttribute(
      "delayTime",
      Integer.toString(timeBetweenFramesMS / 10));
    graphicsControlExtensionNode.setAttribute(
      "transparentColorIndex",
      "0");
 
    IIOMetadataNode commentsNode = getNode(root, "CommentExtensions");
    commentsNode.setAttribute("CommentExtension", "Created by MAH");
 
    IIOMetadataNode appEntensionsNode = getNode(
      root,
      "ApplicationExtensions");
 
    IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");
 
    child.setAttribute("applicationID", "NETSCAPE");
    child.setAttribute("authenticationCode", "2.0");
 
    int loop = loopContinuously ? 0 : 1;
 
    child.setUserObject(new byte[]{ 0x1, (byte) (loop & 0xFF), (byte)
      ((loop >> 8) & 0xFF)});
    appEntensionsNode.appendChild(child);
 
    imageMetaData.setFromTree(metaFormatName, root);
 
    gifWriter.setOutput(outputStream);
 
    gifWriter.prepareWriteSequence(null);
  }
 
  public void writeToSequence(RenderedImage img) throws IOException {
    gifWriter.writeToSequence(
      new IIOImage(
        img,
        null,
        imageMetaData),
      imageWriteParam);
  }
 
  /**
   * Close this GifSequenceWriter object. This does not close the underlying
   * stream, just finishes off the GIF.
   */
  public void close() throws IOException {
    gifWriter.endWriteSequence();    
  }
 
  /**
   * Returns the first available GIF ImageWriter using 
   * ImageIO.getImageWritersBySuffix("gif").
   * 
   * @return a GIF ImageWriter object
   * @throws IIOException if no GIF image writers are returned
   */
  private static ImageWriter getWriter() throws IIOException {
    Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif");
    if(!iter.hasNext()) {
      throw new IIOException("No GIF Image Writers Exist");
    } else {
      return iter.next();
    }
  }
 
  /**
   * Returns an existing child node, or creates and returns a new child node (if 
   * the requested node does not exist).
   * 
   * @param rootNode the <tt>IIOMetadataNode</tt> to search for the child node.
   * @param nodeName the name of the child node.
   * 
   * @return the child node, if found or a new node created with the given name.
   */
  private static IIOMetadataNode getNode(
      IIOMetadataNode rootNode,
      String nodeName) {
    int nNodes = rootNode.getLength();
    for (int i = 0; i < nNodes; i++) {
      if (rootNode.item(i).getNodeName().compareToIgnoreCase(nodeName)
          == 0) {
        return((IIOMetadataNode) rootNode.item(i));
      }
    }
    IIOMetadataNode node = new IIOMetadataNode(nodeName);
    rootNode.appendChild(node);
    return(node);
  }
 
  /**
  public GifSequenceWriter(
       BufferedOutputStream outputStream,
       int imageType,
       int timeBetweenFramesMS,
       boolean loopContinuously) {
 
   */
 
  public static void main(String[] argsd) throws Exception {
	 String images[] = {"c://temp//1.jpg","c://temp//2.jpg","c://temp//3.jpg","c://temp//4.jpg","c://temp//final.gif"};
    if (images.length > 1) {
      // grab the output image type from the first image in the sequence
      BufferedImage firstImage = ImageIO.read(new File(images[0]));
 
      // create a new BufferedOutputStream with the last argument
      ImageOutputStream output = 
        new FileImageOutputStream(new File(images[images.length - 1]));
 
      // create a gif sequence with the type of the first image, 1 second
      // between frames, which loops continuously
      GifSequenceWriter writer = 
        new GifSequenceWriter(output, firstImage.getType(), 1000, true);
 
      // write out the first image to our sequence...
      writer.writeToSequence(firstImage);
      for(int i=1; i<images.length-1; i++) {
        BufferedImage nextImage = ImageIO.read(new File(images[i]));
        writer.writeToSequence(nextImage);
      }
 
      writer.close();
      output.close();
    } else {
      System.out.println(
        "Usage: java GifSequenceWriter [list of gif files] [output file]");
    }
  }
}

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *