dragon66 / icafe

Java library for reading, writing, converting and manipulating images and metadata
Eclipse Public License 1.0
204 stars 58 forks source link

Write animated GIF frames one at a time #14

Closed dragon66 closed 9 years ago

dragon66 commented 9 years ago

In order to reduce memory consumption, there should be a way to write animated GIF frames one at a time. Currently, "icafe" write them from an array of BufferedImages which could be a problem if lots of frames are involved or the frames are large.

dragon66 commented 9 years ago

Done! Now we can write animated GIF like this assuming we have two BufferedImage image1 and image2

    // Start writing animated GIF frame by frame to save memory
    GIFWriter animatedGIFWriter = new GIFWriter();
    aimatedGIFWriter.setImageParam(ImageParam.getBuilder().applyDither(true).ditherThreshold(18).build());
    // Set logical screen width and height to zero to use first frame width and height 
    GIFTweaker.prepareForWrite(animatedGIFWriter, fout, 0, 0);
    GIFTweaker.writeFrame(animatedGIFWriter, fout, image1);
    GIFTweaker.writeFrame(animatedGIFWriter, fout, image2);
    // wrap it up
    GIFTweaker.finishWrite(fout);

One problem with this approach is the logical screen descriptor dimension cannot be determined automatically. We can set the screen width and height explicitly. If either or both of them are less or equal to 0, values from the first frame will be used.