拓展方法形式,传入文件夹的路径可以将文件夹下的全部gif转换为序列帧图片,分为三种形式,散装图片,横向排列图片,纵向排列图片。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace GifToImage.Script
{
public static class Utils
{
public static void GifToImage(this string path)
{
foreach (var info in path.GetTotalGifFileInfo())
{
var directory = info.GetFullPathWithoutExtension();
if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
var image = Image.FromFile(info.FullName);
var dimension = new FrameDimension(image.FrameDimensionsList[0]);
var frameCount = image.GetFrameCount(dimension);
int width = image.Width, height = image.Height;
Bitmap
row = new Bitmap(width * frameCount, height),//横向排列
column = new Bitmap(width, height * frameCount);//纵向排列
for (int i = 0; i < frameCount; i++)
{
image.SelectActiveFrame(dimension, i);
var currentFrameImage = new Bitmap(image);//单帧图片
currentFrameImage.Save($"{directory}/{info.GetNameWithoutExtension()}_{i}.png", ImageFormat.Png);
for (int j = 0; j < width; j++)
for (int k = 0; k < height; k++)
{
var color = currentFrameImage.GetPixel(j, k);
row.SetPixel(i * width + j, k, color);
column.SetPixel(j, i * height + k, color);
}
currentFrameImage.Dispose();//额外补充
}
row.Save($"{directory}/{info.GetNameWithoutExtension()}_row.png", ImageFormat.Png);
column.Save($"{directory}/{info.GetNameWithoutExtension()}_column.png", ImageFormat.Png);
row.Dispose();
column.Dispose();
image.Dispose();
}
}
public static IEnumerable<FileInfo> GetTotalGifFileInfo(this string path) =>
!Directory.Exists(path) ? new FileInfo[0] : InternalGetTotalGifFileInfo(new DirectoryInfo(path));
private static IEnumerable<FileInfo> InternalGetTotalGifFileInfo(this DirectoryInfo info) =>
info.GetDirectories().SelectMany(InternalGetTotalGifFileInfo)
.Concat(info.GetFiles().Where(e => Equals(e.Extension, ".gif")));
public static string GetFullPathWithoutExtension(this FileInfo fileInfo)
{
if (fileInfo == null) return null;
var fullName = fileInfo.FullName;
var indexOf = fullName.LastIndexOf('.');
return indexOf != -1 ? fullName.Substring(0, indexOf) : fullName;
}
public static string GetNameWithoutExtension(this FileInfo fileInfo)
{
if (fileInfo == null) return null;
var name = fileInfo.Name;
var indexOf = name.LastIndexOf('.');
return indexOf != -1 ? name.Substring(0, indexOf) : name;
}
public static T Log<T>(this T t)
{
System.Diagnostics.Debug.WriteLine(t);
return t;
}
public static void Show(params object[] objects) => MessageBox.Show(string.Join("\n", objects));
}
}