Import java.io.*;
Import java.awt.*;
Import java.awt.image.*;
/** * Class animatedgifencoder-encodes a GIF file consisting of one or more frames.
* <pre> * Example: * Animatedgifencoder e = new Animatedgifencoder ();
* E.start (OutputFileName); * E.setdelay (1000);
1 frame per sec * E.addframe (IMAGE1);
* E.addframe (IMAGE2);
* E.finish (); * </pre> * No Copyright asserted on the source code of this class. May is used * for any purpose, however, refer to the Unisys LZW A for patent * on use of the restrictions associated Coder class.
Please forward any corrections * to kweiner@fmsware.com. * @author Kevin Weiner, FM Software * @version 1.03 November 2003 * */public class Animatedgifencoder {PROTECTE d int width;
Image size protected int height; protected Color transparent = null; Transparent color if given protected int transindex; Transparent index in color table protected int repeat =-1; No repeat Protected int delay = 0; Frame delay (hundredths) Protected Boolean started = false;
Ready to output frames protected outputstream out; protected bufferedimage image; Current frame protected byte[] pixels; BGR byte array from frame protected byte[] indexedpixels; Converted frame indexed to palette protected int colordepth; Number of bit planes protected byte[] colortab; RGB palette protected boolean[] Usedentry = new boolean[256]; Active palette entries protected int palsize = 7; Color table size (bits-1) protected int dispose =-1; Disposal code ( -1 = Use default) Protected Boolean closestream = false;
Close stream when finished protected boolean firstframe = true; protected Boolean sizeset = false; If False, get size from the protected int sample = 10; Default sample interval for Quantizer/** * Sets The delay time between each frame, or changes it * for Subsequen
T Frames (applies to last frame added). * * @param ms INT delay time in milliseconds * * public void Setdelay (int ms) {delay = Math.Round (ms/10.0f); }/** * Sets the GIF frame disposal code for the last added frame * and any subsequent frames.
The Default is 0 if no transparent * color has been set, otherwise 2.
* @param code int Disposal code.
*/public void setdispose (int code) {if (code >= 0) {dispose = code; }/** * Sets the number of times the set of GIF frames * should is played. Default is 1; 0 means play * indefinitely.
Must be invoked before the ' the ' the ' the ' the ' the ' the '.
* @param iter int number of iterations.
* @return */public void setrepeat (int iter) {if (ITER >= 0) {repeat = iter;
}/** * Sets the transparent color for the last added frame * and any subsequent frames. * Since all colors are subject to modification * The quantization process, the color in the final * palette for EAC H frame closest to the given color * becomes the TranspareNT color for that frame.
* May is set to NULL to indicate no transparent color.
* * @param c Color to is treated as transparent on display.
*/public void settransparent (Color c) {transparent = C; }/** * Adds next GIF frame. The frame is not written immediately, but are * actually deferred until the next frame is received so that timing * dat A can be inserted. Invoking <code>finish () </code> flushes all * frames.
IF <code>setSize</code> am not invoked, the size of the * the the the the the the the the the the the the ' is used to all subsequent frames.
* * @param im bufferedimage containing frame to write.
* @return True if successful.
*/Public Boolean addframe (BufferedImage im) {if (im = = null) | |!started) {return false;
Boolean OK = true;
try {if (!sizeset) {//Use the SetSize (Im.getwidth (), Im.getheight ()) for the size of the.
image = IM; Getimagepixels (); Convert to correct format if necessary analyzepixels (); BUild color table & map pixels if (firstframe) {WRITELSD ();//Logical Screen Descriptior writepalette ();
/Global Color table if (repeat >= 0) {//Use NS app extension to indicate Reps writenetscapeext (); } writegraphicctrlext (); Write graphic Control extension Writeimagedesc (); Image descriptor if (!firstframe) {Writepalette ();//local Color Table} writepixels ();
Encode and write pixel data Firstframe = false;
catch (IOException e) {ok = false;
return OK;
/** * Flushes any pending data and closes output file.
* If writing to a outputstream, the stream is not * closed.
* * Public Boolean finish () {if (!started) return false;
Boolean OK = true;
started = false;
try {out.write (0x3b);//GIF trailer out.flush ();
if (Closestream) {out.close ();
The catch (IOException e) {ok = false;
}//reset for subsequent use Transindex = 0;
out = null; IMage = null;
pixels = null;
Indexedpixels = null;
Colortab = null;
Closestream = false;
Firstframe = true;
return OK; }/** * Sets frame rate in frames per second.
Equivalent to * <code>setdelay (1000/fps) </code>. * * @param fps float frame rate (frames per second) */public void setframerate (float fps) {if (fps!= 0f) {de
Lay = Math.Round (100f/fps); }/** * Sets quality of color quantization (conversion of images * to the maximum 256 colors allowed by the GIF
Specification). * Lower VALUES (minimum = 1) produce better colors, but slow * processing significantly. The is the default, and produces * good a color mapping at reasonable speeds.
Values Greater * than don't yield significant improvements in speed.
* * @param quality int greater than 0.
* @return */public void setquality (int quality) {if (Quality < 1) quality = 1;
Sample = quality; }/** * Sets the GIF frame size. The default size Is the * size of the ' the ' the ' the ' the ' added if this ' is ' * not invoked.
* * @param w int frame width.
* @param h int frame width.
*/public void setSize (int w, int h) {if (started &&!firstframe) return;
width = w;
Height = h;
if (width < 1) width = 320;
if (height < 1) height = 240;
Sizeset = true; }/** * Initiates GIF file creation on the given stream.
The stream * is not closed automatically.
* * @param os outputstream on which GIF images are written.
* @return False if initial write failed.
*/Public Boolean start (OutputStream os) {if (OS = null) return false;
Boolean OK = true;
Closestream = false;
out = OS;
try {writestring ("gif89a");//header} catch (IOException e) {ok = false;
return started = OK;
}/** * Initiates writing of a GIF file with the specified name.
* * @param file String containing output file name.
* @return False if Open or initial write failed. * Public Boolean Start (String file) {Boolean OK = true;
try {out = new Bufferedoutputstream (new FileOutputStream (file));
OK = start (out);
Closestream = true;
catch (IOException e) {ok = false;
return started = OK;
/** * Analyzes image colors and creates color map.
* * protected void Analyzepixels () {int len = pixels.length;
int npix = LEN/3;
Indexedpixels = new Byte[npix];
Neuquant NQ = new Neuquant (pixels, Len, sample); Initialize Quantizer Colortab = nq.process (); Create reduced palette//Convert map from BGR to RGB for (int i = 0; i < colortab.length; i + 3) {byte tem
p = colortab[i];
Colortab[i] = colortab[i + 2];
Colortab[i + 2] = temp;
USEDENTRY[I/3] = false;
}//map image pixels to new palette int k = 0;
for (int i = 0; i < Npix i++) {int index = NQ.MAP (pixels[k++] & 0xFF, pixels[k++] & 0xFF,
pixels[k++] & 0xff);
Usedentry[index] = true; Indexedpixels[i] = (BYTE) index;
} pixels = null;
colordepth = 8;
Palsize = 7; Get closest match to transparent color if specified if (transparent!= null) {Transindex = Findclosest (transparen
T); }/** * Returns index of palette color closest to c * */protected int findclosest (color c) {if (colortab
= = null) return-1;
int r = c.getred ();
int g = C.getgreen ();
int b = C.getblue ();
int minpos = 0;
int dmin = 256 * 256 * 256;
int len = colortab.length; for (int i = 0; i < Len;)
{int dr = R-(colortab[i++] & 0xff);
int dg = G-(colortab[i++] & 0xff);
int db = B-(Colortab[i] & 0xff);
int d = dr * Dr + DG * DG + DB * DB;
int index = I/3;
if (Usedentry[index] && (D < dmin)) {dmin = D;
Minpos = index;
} i++;
return minpos; /** * Extracts image pixels into byte array "Pixels" */protected void Getimagepixels () {int w = Image.getwid
Th ();
int h = image.getheight (); int type = Image.gettype (); if (w!= width) | | (h!= height) | | (Type!= BUFFEREDIMAGE.TYPE_3BYTE_BGR)) {//Create new image with right Size/format bufferedimage temp = new BufferedImage (width, height, bufferedimage .
TYPE_3BYTE_BGR);
Graphics2D g = temp.creategraphics ();
G.drawimage (image, 0, 0, NULL);
Image = temp;
} pixels = ((databufferbyte) Image.getraster (). Getdatabuffer ()). GetData (); }/** * writes Graphic control Extension/protected void Writegraphicctrlext () throws IOException {Out.write ( 0X21); Extension introducer Out.write (0XF9); GCE label Out.write (4);
Data block size int TRANSP, disp;
if (transparent = = null) {TRANSP = 0; DISP = 0;
Dispose = no action} else {TRANSP = 1; DISP = 2; Force clear if using transparent color} if (Dispose >= 0) {disp = dispose & 7;//user override} D
ISP <<= 2;
Packed fields Out.write (0 |//1:3 Reserved disp |//4:6 DISPOSAL 0 | 7 User input-0 = none transp); 8 Transparency Flag Writeshort (delay); Delay x 1/100 sec out.write (Transindex); Transparent Color index out.write (0); Block Terminator}/** * writes Image descriptor/protected void Writeimagedesc () throws IOException {out . write (0x2c); Image separator Writeshort (0);
Image position X,y = 0,0 writeshort (0); Writeshort (width);
Image size Writeshort (height);
Packed fields if (firstframe) {//No LCT-GCT is used for a (or only) frame Out.write (0);
else {//Specify normal LCT out.write (0x80 |//1 Local color table 1=yes 0 |//2 INTERLACE-0=NO 0 | 3 Sorted-0=no 0 | 4-5 reserved palsize); 6-8 size of color table}/** * writes Logical screen descriptor/protected void WRITELSD () throws
Eption {//Logical screen size writeshort (width);
Writeshort (height); Packed fields Out.write (0x80 | 1:global color Table flag = 1 (GCT used) 0x70 | 2-4: Color Resolution = 7 0x00 | 5:GCT Sort flag = 0 palsize)); 6-8: GCT size out.write (0); Background color index out.write (0);
Pixel Aspect Ratio-assume 1:1}/** * writes Netscape application extension to define * repeat count. * * protected void Writenetscapeext () throws IOException {out.write (0x21);//Extension introducer-out.write (0xff); /app Extension label Out.write (11); Block size writestring ("NETSCAPE" + "2.0"); App ID + auth code out.write (3); Sub-block size out.write (1); Loop sub-block ID writeshort (repeat); Loop count (extra iterations, 0=repeat Forever) out.write (0); Block Terminator}/** * writes color table */protected void Writepalette () throws IOException {Out.write (
Colortab, 0, colortab.length);
int n = (3 * 256)-colortab.length;
for (int i = 0; i < n; i++) {out.write (0);
}
}
/*** Encodes and writes pixel data */protected void WritePixels () throws IOException {Lzwencoder encoder = new Lzwe
Ncoder (width, height, indexedpixels, colordepth);
Encoder.encode (out); /** * Write 16-bit value to output stream, LSB A/protected void Writeshort (int value) throws
On {out.write (value & 0xff);
Out.write ((Value >> 8) & 0xff); }/** * writes string to output stream/protected void WriteString (string s) throws IOException {for (int i = 0; I < s.length ();
i++) {out.write ((byte) S.charat (i));
}
}
}