Click here to Skip to main content
15,890,557 members
Articles / Mobile Apps
Article

NGif, Animated GIF Encoder for .NET

Rate me:
Please Sign up or sign in to vote.
4.02/5 (58 votes)
1 Sep 2005CPOL 1.5M   18K   117   123
Create animated GIF images using C#.

Sample Image - NGif.gif

Introduction

Because .NET Framework can't create animated GIF images, NGif provides a way to create GIF animations in the .NET framework. It can create an animated GIF from several images and extract images from an animated GIF.

Using the code

C#
/* create Gif */
//you should replace filepath
String [] imageFilePaths = new String[]{"c:\\01.png","c:\\02.png","c:\\03.png"}; 
String outputFilePath = "c:\\test.gif";
AnimatedGifEncoder e = new AnimatedGifEncoder();
e.Start( outputFilePath );
e.SetDelay(500);
//-1:no repeat,0:always repeat
e.SetRepeat(0);
for (int i = 0, count = imageFilePaths.Length; i < count; i++ ) 
{
 e.AddFrame( Image.FromFile( imageFilePaths[i] ) );
}
e.Finish();
/* extract Gif */
string outputPath = "c:\\";
GifDecoder gifDecoder = new GifDecoder();
gifDecoder.Read( "c:\\test.gif" );
for ( int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++ ) 
{
 Image frame = gifDecoder.GetFrame( i ); // frame i
 frame.Save( outputPath + Guid.NewGuid().ToString() 
                       + ".png", ImageFormat.Png );
}

Points of Interest

Use Stream to replace BinaryWriter when you write a fixed-byte structured binary file.

History

  • 31 Aug 2005: Draft.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
China China
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: "The process cannot access the file xpto because it is being used by another process". Pin
Rassler481-Mar-13 1:16
Rassler481-Mar-13 1:16 
QuestionCan I release a derived work please? Pin
sbridewell4-Sep-09 9:12
sbridewell4-Sep-09 9:12 
AnswerRe: Can I release a derived work please? Pin
jambonbill6-Oct-09 3:04
jambonbill6-Oct-09 3:04 
GeneralRe: Can I release a derived work please? Pin
sbridewell6-Oct-09 10:54
sbridewell6-Oct-09 10:54 
GeneralRe: Can I release a derived work please? Pin
jambonbill6-Oct-09 14:50
jambonbill6-Oct-09 14:50 
GeneralRe: Can I release a derived work please? [modified] Pin
sbridewell7-Oct-09 9:10
sbridewell7-Oct-09 9:10 
GeneralResize an animated gif background transparency Pin
vuivuivui26-Aug-09 21:23
vuivuivui26-Aug-09 21:23 
Questionhow to force no transparency Pin
Are Jay20-Aug-09 7:55
Are Jay20-Aug-09 7:55 
Thank you for the open source code. Works like a champ!!!

I have run into an issue with a few of the animated gifs having a transparent background when they should NOT have a transparent background.

Can I re-enforce no transparent background during the resizing process?

My implementation of your open source code...
string _tempID = Path.GetFileNameWithoutExtension(_file);

string _path = String.Format(@"~/assets/images/temp/{0}/{1}", this.Session.SessionID, _tempID.ToString());
_path = Server.MapPath(_path);
if (!System.IO.Directory.Exists(_path))
	System.IO.Directory.CreateDirectory(_path);

GifDecoder _gifDecoder = new GifDecoder();
_gifDecoder.Read(_file);

for (int i = 0, count = _gifDecoder.GetFrameCount(); i < count; i++)
{
	System.Drawing.Image frame = _gifDecoder.GetFrame(i);  // frame i
	frame.Save(String.Format(@"{0}\{1}.png", _path, Guid.NewGuid().ToString()), ImageFormat.Png);
}

AnimatedGifEncoder _encoder = new AnimatedGifEncoder();
_encoder.SetTransparent(Color.Empty);

// make a memory stream to work with the image bytes
using (FileStream imageStream = 
	new FileStream( _path + @"\temp.gif" ,FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
	_encoder.Start(imageStream);
	_encoder.SetDelay(_gifDecoder.GetDelay(0)); // time between images			
	_encoder.SetRepeat(0); //-1:no repeat,0:always repeat

	string[] _imagePaths = System.IO.Directory.GetFiles(_path, "*.png");

	for (int i = 0, count = _imagePaths.Length; i < count; i++)
		_encoder.AddFrame(this.resize(_imagePaths[i], newWidth, newHeight, _increaseImageSize));

	// make byte array the same size as the image
	byte[] imageContent = new Byte[imageStream.Length];

	// rewind the memory stream
	imageStream.Position = 0;

	// load the byte array with the image
	imageStream.Read(imageContent, 0, (int)imageStream.Length);

	// return byte array to caller with image type
	this.Response.ContentType = _contentType;
	this.Response.AddHeader("content-length", System.Convert.ToString(imageStream.Length));

	this.Response.BinaryWrite(imageContent);
}

try
{
  foreach (string _f in System.IO.Directory.GetFiles(_path))
    System.IO.File.Delete(_f);

  System.IO.Directory.Delete(_path);
  System.IO.Directory.Delete(System.IO.Directory.GetParent(_path).ToString());
}
catch (Exception _ex) { Console.Write(_ex.ToString());}

_encoder.Finish();

_encoder = null;
_gifDecoder = null;

this.Response.End();


I'm listening but I only speak GEEK.

Generalit can't store more than 19 frames. Pin
inamgul26-Feb-09 1:00
inamgul26-Feb-09 1:00 
GeneralAnimated gif Timeline Properties Pin
Daffy1012-Nov-08 22:01
Daffy1012-Nov-08 22:01 
Generalan better implement Pin
gOODiDEA.NET13-Oct-08 14:54
gOODiDEA.NET13-Oct-08 14:54 
GeneralRe: an better implement Pin
ecjob21-Oct-08 4:24
ecjob21-Oct-08 4:24 
GeneralRe: an better implement Pin
Spirch2-Jan-09 14:13
Spirch2-Jan-09 14:13 
GeneralRe: an better implement Pin
Ceyhun25-Jul-09 6:20
Ceyhun25-Jul-09 6:20 
GeneralRe: an better implement Pin
Nathanael Jones5-Jan-12 6:33
Nathanael Jones5-Jan-12 6:33 
Question怎样才能把体积减少一些啊?? Pin
ecjob11-Oct-08 8:31
ecjob11-Oct-08 8:31 
General一处bug Pin
interiv@qq.com6-Sep-08 17:05
interiv@qq.com6-Sep-08 17:05 
GeneralExporting frames [modified] Pin
jambonbill17-Aug-08 20:01
jambonbill17-Aug-08 20:01 
GeneralPerformance improvement Pin
Member 21880517-Aug-08 0:00
Member 21880517-Aug-08 0:00 
GeneralRe: Performance improvement Pin
jambonbill14-Aug-08 0:30
jambonbill14-Aug-08 0:30 
GeneralBugfix NextPixel() Pin
Member 21880516-Aug-08 23:49
Member 21880516-Aug-08 23:49 
GeneralRe: Bugfix NextPixel() Pin
PaulNeyman11-Jan-10 1:08
PaulNeyman11-Jan-10 1:08 
GeneralExcellent work! Pin
DigiOz Multimedia18-Jun-08 18:47
DigiOz Multimedia18-Jun-08 18:47 
QuestionThe gif be changed bigger? Pin
tintown_liu25-Dec-07 14:35
tintown_liu25-Dec-07 14:35 
AnswerRe: The gif be changed bigger? Pin
Shobin Mathew9-Jul-08 18:45
Shobin Mathew9-Jul-08 18:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.