使用codeplex的GifCreator来操作
步骤:
一 获取动态链接库Gif.Components.dll
方式1:使用源码编译
第三方的源码地址如下:http://www.codeproject.com/Articles/11505/NGif-Animated-GIF-Encoder-for-NET
这个不好下载,要注册,我搞了好久都没能把它下载下来
方式2:从这位老兄的博客https://www.cnblogs.com/bomo/archive/2013/02/26/2932953.html中有得下载,我找了好久才找到的
方式3:从我的网盘下载(里面还包括了我下面要用到的测试图片):链接:https://pan.baidu.com/s/1INUkPqci-UUAI2wm994PsQ
提取码:4pwa
二 新建一个winfom程序,并拖拽一个Button进去,如下图:
三 把从我的网盘下载的压缩包解压后放到bin/Debug目录下,并添加dll的引用
四 编写程序如下(参考别人的写的):
using Gif.Components; //添加的命名空间
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 多张图片合成Gif
{
public partial class Form1 : Form
{
//用来区分gif保存的路径
int count = 0;
public Form1()
{
InitializeComponent();
}
///
/// 转换多张图片到一张gif
///
/// 多张图片的路径集合
/// 需要保存的gif的路径
/// 每张图片播放的间隔时间
/// 图片的宽度
/// 图片的高度
///
private bool ConvertJpgtoGif(string[] src, string gifPath,int time,int w,int h)
{
try
{
AnimatedGifEncoder el = new AnimatedGifEncoder();
el.Start(gifPath);
el.SetDelay(time);
//0:循环播放 -1:不循环播放
el.SetRepeat(0);
for (int i = 0, count = src.Length; i < count; i++)
{
Image img = Image.FromFile(src[i]);
//如果多张图片的高度和宽度都不一样,可以打开这个注释
//img = ReSetPicSize(img, w, h);
el.AddFrame(img);
}
el.Finish();
return true;
}
catch (Exception e1)
{
//MessageBox.Show(e1.Message);
return false;
}
}
///
/// 重新调整图片的大小,使其满足要求
///
///
///
///
///
private Image ReSetPicSize(Image image, int newW, int newH)
{
Bitmap bmp = new Bitmap(image);
try
{
Bitmap b = new Bitmap(newW, newH);
Graphics g = Graphics.FromImage(b);
// 插值算法的质量
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
g.Dispose();
// return b;
Image img = (Image)b;
// MessageBox.Show("Width"+img.Width.ToString() + "Height:" + img.Height.ToString());
return img;
}
catch
{
return null;
}
}
///
/// 保存按钮点击事件
///
///
///
private void btnSave_Click(object sender, EventArgs e)
{
//图片的路径集合
string[] srcPath = { "image/jiafei1.jpg", "image/jiafei2.jpg", "image/jiafei3.jpg", "image/jiafei4.jpg", "image/jiafei5.jpg" };
//转换后gif的保存路径,在Debug/bin目录下
string gitPath = "test" + count + ".gif";
//用来区分gif保存的路径
count++;
try
{
//开始转换
ConvertJpgtoGif(srcPath, gitPath, 1000, 800, 600);
MessageBox.Show("保存成功");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
}
}
效果如下:
注意:转换耗时很长,建议开一个新的线程,我就5张图片,合成一张gif却耗时了5秒,不是我想要的效果