使用codeplex的GifCreator http://gifcreator.codeplex.com 来处理Gif文件
引用库文件Gif.Components.dll
1、把Gif文件转成Png文件
/// <summary> /// 把Gif文件转成Png文件,放在directory目录下 /// </summary> /// <param name="file"></param> /// <param name="directory"></param> /// <returns></returns> public static void GifToPngs(string giffile, string directory) { GifDecoder gifDecoder = new GifDecoder(); directory += "\\"; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } //读取 gifDecoder.Read(giffile); for (int i = 0, count = gifDecoder.GetFrameCount(); i < count; i++) { Image frame = gifDecoder.GetFrame(i); // frame i frame.Save(directory + "\\" + i.ToString("d2") + ".png", ImageFormat.Png); //转成jpg //frame.Save(directory + "\\" + i.ToString("d2") + ".jpg", ImageFormat.Jpeg); } }
2、把多张Png文件转成Gif文件
/// <summary> /// 把directory文件夹里的png文件生成为gif文件,放在giffile /// </summary> /// <param name="directory">png文件夹</param> /// <param name="giffile">gif保存路径</param> /// <param name="time">每帧的时间/ms</param> /// <param name="repeat">是否重复</param> public static void PngsToGif(string directory, string giffile, int time, bool repeat) { //一般文件名按顺序排 string[] pngfiles = Directory.GetFileSystemEntries(directory, "*.png"); AnimatedGifEncoder e = new AnimatedGifEncoder(); e.Start(giffile); //每帧播放时间 e.SetDelay(500); //-1:不重复,0:重复 e.SetRepeat(repeat?0:-1); for (int i = 0, count = pngfiles.Length; i < count; i++) { e.AddFrame(Image.FromFile(pngfiles[i])); } e.Finish(); }
由于Gif的转换和生成速度比较慢,所以一般放在新的线程进行操作
库文件
http://files.cnblogs.com/bomo/Gif.Components.zip