I have to admit that I just love animated GIF's, it reminds me the old school days playing the SNES
Recently I found a java GIF encoder and decided to implement it in AS3, ok maybe some people will say it's just unuseful but here it is, I love it !
Everything is encoded through the player. Then you know the story, the GIF stream is sent through AMFPHP to a server to download it, and then save it to your hard disk. Any kind of images can be included in the final GIF, each frame is a flash.display.BitmapData object.
I'll post the sources in a few days, I want to add some more features, stay tuned !
Piterwilson did a funny experiment with this and the GIFPlayer class.
Here is how to generate an animated GIF stream in ActionScript 3 :
// we create the GIF encoder var myGIFEncoder:GIFEncoder = new GIFEncoder(); // we call the start method to start a new GIF file stream myGIFEncoder.start(); // we call the setRepeat method with 0 as parameter so that it loops myGIFEncoder.setRepeat(0); //we specify each frame delay in ms before each addFrame call myGIFEncoder.setDelay ( 100 ); //we add each BitmapData as frames with the addFrame method myGIFEncoder.addFrame( new BitmapData ( 200, 200 ) ); // we finalize the GIF stream by calling the finish method myGIFEncoder.finish(); // then you retrieve the GIF ByteArray with the stream getter var myGIFStream:ByteArray = myGIFEncoder.stream;
Online Demo :
The GIF Encoder looks nice on the Web Flash Festival 2007 screen

This work is licensed under a Creative Commons Attribution 3.0 License.
Sources and documentation available at http://code.google.com/p/as3gif/
Comments (61)
This is a cool project. I can think to some good things to do with it.
For the moment, the algorythm do not optimize well consecutives frames. If you use the same image in two consecutives frames, the generated image will almost be twice the size of the imagegenerated with only one frame with this image.
I’m sure that the animated GIF algorythm could help you to do some optimizations not to include the same area in two (or more) consecutives frames when they are the same because most of the animated GIF software use this option.
Hi Tek,
yes i’m going to double check that, I will also include some more features
Some crazy things to do with this project.
cheers
Hi Thibault Imbert.
I dare say this is NOT unuseful. Actually, one of my colleagues is developing a animated GIF encoder too.
Regards.
Hi Han,
Glad to hear that
It seems that we all have ideas about what to do with it
I’ve read a little what can be found on the internet and look at what my animated GIF edition tool (Jasc Animation Shop) could do. The best is simply the GIF specification : http://members.aol.com/royalef/gif87a.txt
In fact, animated GIF do not offer a real way to create special frames for optimization, like video with I, P, B-frames. This can only be a succession of simple GIF image block.
For consecutive images that are exactly the same, the optimization is simply to combine the duration of the display of the two images … not too complicated
For the optimisation between two or more different consecutive frames, you must know that display on the screen of the GIF renderer must only be refreshed at the end and the start of the animation.
It means that pixels that are not specifically redrawn by a frame will stay the same all the animation long.
It is possible to use images that are not the same size and position (top,left) between each frame and you can position them the way you want. The optimisation is so to use images in frames that only define the changed area. To define several changed area on the same image you can use several frames with images of different position and size separated by a zero delay, the renderer will display them as a single image.
Animation Shop Pro also use the transparent color on non-transparent GIF images to store the unchanged area. This process that can be quite simple for you to use and a better optimization for the file size if you decide not to offer transparent GIF images.
But as said in private, the optimization could wait … it does what it says for the moment
Guys, you keep impressing
thanks for the effort and can’t wait to see more of it.
Love it (and love the funky sample) !
Tanks a lot…
hehe yes Bob,
we love it foonky
I could use just a regular non animated gif encoder. Is there anyway you could post an encoder for non animated gifs? Or, if you could just let me know where you found the gif encoding algorithm that would be helpful too. About how long did it take you to convert it to AS3?
Hi Andrew,
If you want to encode unanimated GIF, the actual GIF class I did has a addFrame method that takes an incoming flash.display.Bitmap object to compose each frame from the GIF.
Just don’t add more than one frame and that’s it, I’ll post all the sources and references on tuesday
cheers
Very useful i think. Here’s something quick i put together with you gif encoder/player. Requires a webcam and flash9.
Thanks for this encoder, i look forward to more.
url:
http://www.piterwilson.com/wcsmt/index.html
(Embarasing, forgeting to copy+paste)
Hi Piterwilson,
Thanks for the link, it’s very nice and funny
Love to see those classes used in a funny way
Hi,
I’m trying to use this on my local server, but I can’t figure out how to make the PHP code to store the GIF file. I’m thinking I just need to store the stream, but I’m not that good with PHP.
Could you post that part as well?
It works the same way as the jpg encoder php code.
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
/ /get the binary stream
$im = $GLOBALS["HTTP_RAW_POST_DATA"];
$file=”myfile.gif”;
$fp = fopen($file, ‘wb’);
fwrite($fp, $im);
fclose($fp);
}
Thanks a lot! didn’t know it was that simple..
Thanks Piterwilson for helping Michel
hello
i saw the little project of yours, can you share sources for the webcam / gif secvence?
sorry for my bad english
sry 4 double post, i was adressing to mr. Piterwilson i hope he’s watching this thread… i have an ideea on making a video sequencer but i need a point to start for a school project. Thanks.
A heads up for AMFPHP users. Almost started to pull my hair out on this one.
Your objectEncoding should be set to AMF3, not AMF0, otherwise you will get a 0kb gif file.
I also created GIFEncoder ( III 2007 )
All frames capturef from WebCam @ 160×120
20 frames
My: 27 s – 340kb
Your: 31 s – 284kb
5 frames:
My: 5s – 88kb
Your: 8s – 72kb
Sir,
when will u put the source of AS3 GIF Animation Encoding Class
i don’t know anything about AMFPHP so want that in order to save any gif.
so, please let me know when u put that source
thanks
Hey,
The project I am working on requires animated gifs. I need load, create/change and save animated gifs.
Is there any chance you’ll chare this source?
I am also willing to pay for it, if there any substansial code behind.
In any case any help would be very appreciated.
Hi Evgeny,
You can everything you need here :
http://code.google.com/p/as3gif/
let me know if it works smoothly
regards,
Thibault
Many thanks for such prompt reply.
Really!
I will check it out and let you know.
Hi Thibault,
Do I need to connect to your gateway?
I also see the “gifencoder.GIFEncoder.saveToServer” call. Is there a way to bypass it?
Kind regards,
Evgent
Hi,
I use AMFPHP to save the GIF on the server and retrive it later.
You can download AMFPHP and use it the same way I did.
http://www.amfphp.org
If you have problems setting up everything, I can send you an example.
regards,
Thibault
Well. I am not familiar with AMPPHP, thus if you have anything under your hand, I would appreciate it very much.
What if I would like to save it locally?
Hi,
i’m really impressed by gif encoder. thank you.
But i have a little problem.
Finish gif is so big
Where a real gif optimisation?
Are there any parameters of oprimisation in your class?
Thank you and sorry for may bad eng.
The performance is very slow and I get bytesAvailable = 0 in the debugger. I’m building my own sample with two BitmapData objects 400×400 size. Any ideas?
Mr ByteArray,
As you know i have been enjoying and using your classes a lot and i have run into a limitation and im trying to find where to look for information on where to bypass it.
When i use this gif loader to load a very large animation, something above 2mb or so, it starts to ‘stall’ and fail to load depending on the user’s machine (i think).
I have traced this problem to be triggered by the time out error which seems to come from the bytearray class (am i right?) probably line 508 of the GIFDecoder.as source file.
Im trying to find out if there is a way to extend the time limit in which a time out is declared so that really long animations can be loaded without problem.
Any ideas? If you can give me any tips on where to look, and if its possible at all, i would gladly implement a fix so the class is more stable.
I also had some problems with the currentFrame being updated a bit later than needed but this is minor and can be fixed no problem.
Thanks.
Sorry to double post, but in case anyone ahs the same problem i believe there are 2 ways to fix:
1- i found out you can modify the script time out limit in the flash publish settings (duh!)
2- i believe the GIFDecoder class on the read() method attempts to read everything at once (in ‘while’ loop), this is very bold of the class! a more sensible approach could be to instead use a ENTER_FRAME or TIMER event to do only one loop per frame (or one loop every so many miliseconds) and ease the load (even if it takes a bit longer) so that not THE WHOLE GIF has to be decoded at once
Hi there – I’m confused about how to save a .gif locally – with the “generate gif” button you have there. i don’t see that button in the file i downloaded. i simply want to allow people to download a gif of the current stage. is this possible with your code?
Hi,
I?m trying to use this on my local server, but I can?t figure out how to make the PHP code to store the GIF file.I have trying to use this plan:
if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
/ /get the binary stream
$im = $GLOBALS["HTTP_RAW_POST_DATA"];
$file=?myfile.gif?;
$fp = fopen($file, ?wb?);
fwrite($fp, $im);
fclose($fp);
}
But it is also cannot save GIF stream,I know how to using amfphp,but I don”t know how to save it ,can u shared your php code ? or give me some solvent.
thank!
ps:/ sorry my bad English
this is so KOOL!
but now with the flash player 10 and the great filereference,
it is possible to save with the filerefence.save() a GIF animated file without using PHP server side?
Hi gino,
Of course we can ! That is the cool thing with the Flash Player 10, no more server-side round tripping.
best,
Thibault
Hello,
I need HELP. Im using AMFPHP to save GIF file, but the file size is always 0 bytes(objectEncoding=AMF3). Somebody helpme?
Sorry for my bad english.
Codes:
//////
AS3:
import org.gif.encoder.GIFEncoder;
import flash.net.NetConnection;
import flash.net.ObjectEncoding;
//
var myService:NetConnection = new NetConnection();
myService.objectEncoding = ObjectEncoding.AMF3;
myService.connect(“http://www.abarbearia.com.br/amfphp/gateway.php”);
var myResponder:Responder = new Responder (onSuccesso, onErro);
function onSuccesso(responds:Object):void {
tstatus.text = “ok” + responds;
};
function onErro(responds:Object):void {
tstatus.text = “error” + responds;
};
botao.addEventListener(MouseEvent.CLICK, _fbclick);
function _fbclick(e:MouseEvent):void{
var bmp1:BitmapData = new BitmapData (f1.width,f1.height);
bmp1.draw(f1);//f1 – MovieClip to save
//
var myGIFEncoder:GIFEncoder = new GIFEncoder();
//
myGIFEncoder.start();
myGIFEncoder.setRepeat(0);
myGIFEncoder.setDelay (100);
myGIFEncoder.addFrame(bmp1);
myGIFEncoder.finish();
//
var myGIFStream:ByteArray = myGIFEncoder.stream;
var streamObject:Object = {gifstream : myGIFStream};
myService.call (“gifencoder.GIFEncoder.saveToServer”, myResponder, [streamObject] );
};
SERVICE – PHP
data property
$imageData = $bytearray->data;
$idimage = date(“U”) . “.gif”;
return ( $success = file_put_contents(“../../../lab/gifs/”.$idimage, $imageData) ) ? $idimage : $success;
}
}
?>
Sorry for double post.
The PHP code is:
data property
$imageData = $bytearray->data;
$idimage = date(“U”) . “.gif”;
return ( $success = file_put_contents(“../../../lab/gifs/”.$idimage, $imageData) ) ? $idimage : $success;
}
}
?>
Thanks!
Hi Thibault,
you can send me the Service(GIFEncoder.php) to use with AMFPHP?
Thanks and sorry for my bad english
When I hit the Generate GIF, I get this error thrown to me by flash player: Certain actions, such as those that display a pop-up window, may only be invoked upon user interaction, for example by a mouse click or button press.
HI Muhammad,
This is due to new FP10 security restrictions, download method from FileReference should not be called outside a keyboard or mouse event. I will update the demo, thanks
Thibault
Hey, I just downloaded this and gave it a shot – seems to work so great job! One thing, the first animated gif I tried loaded but didn’t display, the second one did. So I opened both in Fireworks to see the difference – turned out the first had a transparent background. So, did you know that transparent background gifs don’t display? And do you have a fix for this?
Thanks! -DB
PS – when I exported that first gif back out of Fireworks without the transparent background it played just fine. -DB
How can i resize an existing gif with your components?
I use your gif player to load the gif and then i create an new gif an resize every single bitmap, but this takes to long.
Thanks for help.
Hi,
I am just struggling to combine the encoder with the player. I use your example from above and the resulting byteArray for the GIFPlayer in “loadbytes”. After doing that, totalFrames always returns 0, no matter how many bitmaps I send to the encoder. I can send you the class is you want, nothing complex.
Cheers!
Hi!
Strange, when I use the encoder, the byteArray is always 0 long, no matter how many bitmaps I am adding..
Any idea? (using v0.4)
Ok, I found it, dunno if this is a bug or if I am stupid, but after encoding, you have to set the byte-pointer back to 0:
myGIFEncoder.stream.position = 0;
At least for the Playback.
Hi Kaiser,
Sorry for the late response. Cool you found the problem, I will patch the latest version so that it automatically resets the pointer to 0.
Thanks
Thibault
First i would like to thank you for the gif classes, CUrrently i’m working on an project where i need to save gifs wirh reduced colors – 128,64,32 or 16. Is there an option in the gif encoder class to reduce colors? I have tried a few things – reduced the colors in the NeuQuant Class but that didnt work. What would you do to reduce colors an export an animated gif? I suppose you havve to create a palette of (for example 64 colors) for all frames!?
What about my problem? Will there be a resizing method?
My problem is the color palette for every frame. It takes to much time to calculate it for every frame. Can i take the color palette from the given animation and use it for the resized animation?
Thanks and Greetings
Benjamin
hello!
I am Japanese.
this message was created by Google Translate.
Can I use the commercial?
I’m trying to sell the software with this encoder.
if I can use the commercial I link your page.
I am sorry.
I can not speak English : (
please mail my e-mail address.
Hi my Japanese friend
Of course you can use it commercially. No problem
best,
Thibault
Thank you very much!!
My nickname is Somila.
Nice to meet you!
Can this encoder create a transparent gif?
I can speak a little English:)
When I save the GIF decoder’s stream to a file, it cannot be displayed correctly. Why….
I’ve been using this class in an image editing program I’ve been writing and I’ve noticed a problem. When I load an image with thousands of colors and try to save it as a gif it fails. Is there anyway that I/you could modify this class to allow it to generate pallets when given an obscene number of different colors?
Thank you for your job!
I have some problem. I add 8 frames by this manner:
// creating Array of BitmapData in loop by snap some sprite;
var gifSource:BitmapData = new BitmapData (106, 106, false, 0xf29a9a);
gifSource.draw(spriteCont, null, null, null);
framesArray.push(gifSource);
// then add them to GIF
myGIFEncoder = new GIFEncoder();
myGIFEncoder.start();
myGIFEncoder.setRepeat(0);
myGIFEncoder.setDelay ( 1000 );
myGIFEncoder.addFrame(framesArray[0]);
myGIFEncoder.setTransparent(0xf29a9a);
myGIFEncoder.setDispose(2);
myGIFEncoder.addFrame(framesArray[1]);
myGIFEncoder.addFrame(framesArray[2]);
myGIFEncoder.addFrame(framesArray[3]);
myGIFEncoder.addFrame(framesArray[4]);
myGIFEncoder.addFrame(framesArray[5]);
myGIFEncoder.addFrame(framesArray[6]);
myGIFEncoder.addFrame(framesArray[7]);
myGIFEncoder.finish();
And I have only 3rd frame with transparent background:
http://kalb.ws/temp/some.gif
Can you say me what is wrong.
How to use the transparency of a bitmapdata that already has an alpha channel?
AND If I setTransparent(0×00000000) only a few frames are converted correctly..what’s wrong?
I really need this wonderful class
still no luck, this class doesn’t handle transparency correctly…Thibault can you help?
Thank you for all.
Thibault, Can you help me please?
When I created some a gif, class encoder created stream for a gif, so when I want to play created gif, i use .loadBytes(bytes) method, but it don’t play loaded by stream (((
But .load(url) method perfectly works.
What my wrong?
Hello, thanks for your classes,
but this gifplayer doesn’t handle transparency correctly, what method can be solved?
Trackbacks/Pingbacks (10)
[...] AS3 GIF Animation Encoding Class 0.1 [...]
[...] Player
[...] Imbert is an amazing man! Last year i used his AS3 PDF generation library, and now i used his AS3 GIF Animation Encoding Library to make an online gif89a [...]
[...] ก่อนหน้านี้ ที่เว็ป http://www.bytearray.org ก็มีคลาสที่ใช้ ByteArray มาเพิ่มขีดความสามารถให้แฟลช ด้วยการสร้างคลาสที่จะ แสดงผล GIF Animation ได้ http://www.bytearray.org/?p=95 หรือคลาสที่จะสามารถให้แฟลช สร้างไฟล์ Gif Animation ได้ http://www.bytearray.org/?p=93 [...]
[...] [...]
[...] Actionscript 3 Experiments and Flash Player love
< AS3 GIF Animation Encoding Class 0.1 [ by Thibault Imbert ] Introducing AlivePDF! [...]
[...] [...]
[...] numerous amazing AS3 libraries! Last year i used his AS3 PDF generation library, and now i used his AS3 GIF Animation Encoding Library for an online gif89a [...]
[...] またもやライブラリの作例を改変。 作例がFlashIDE+FlashPlayer9向けなので、FlashDevelop+FlashPlayer10向けに書き換えてみた。要はflaファイルを不要にしたのと、ファイルの保存をFileReferenceのsave()を使うようにした。 そんで、かなりシンプルにして、ライブラリの最新版(0.6)を使うようにした(作例では、0.1)。 [...]
[...] AS3 GIF Animation Encoding Class 0.1 by Thibault Imbert [...]