使用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();
}
/// <summary>
/// 轉換多張圖片到一張gif
/// </summary>
/// <param name="src">多張圖片的路徑集合</param>
/// <param name="gifPath">需要保存的gif的路徑</param>
/// <param name="time">每張圖片播放的間隔時間</param>
/// <param name="w">圖片的寬度</param>
/// <param name="h">圖片的高度</param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 重新調整圖片的大小,使其滿足要求
/// </summary>
/// <param name="image"></param>
/// <param name="newW"></param>
/// <param name="newH"></param>
/// <returns></returns>
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;
}
}
/// <summary>
/// 保存按鈕點擊事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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秒,不是我想要的效果