Skip to content

Instantly share code, notes, and snippets.

@dskjal
Last active November 26, 2017 07:49
Show Gist options
  • Save dskjal/c1c1fc353618241fe178eef83ffde312 to your computer and use it in GitHub Desktop.
Save dskjal/c1c1fc353618241fe178eef83ffde312 to your computer and use it in GitHub Desktop.
アニメーションGIFをjpgに変換するC#プログラム
// BEGIN MIT LICENSE BLOCK //
//
// Copyright (c) 2017 dskjal
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
// END MIT LICENSE BLOCK //
/*
* 使い方
* GIF2JPG gifのファイルパス 出力ディレクトリ(option) ファイルフォーマット(option)
* ファイルフォーマットは jpg bmp gif png tiff が指定できる.デフォルトは jpg
*/
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace GIF2JPG {
class Program {
static void Main(string[] args) {
if(args.Length < 1) {
Console.WriteLine("How to use : "+Environment.NewLine+"GIF2JPG [gif file path] [output directory path(option)][format(option)]");
return;
}
var srcPath = args[0];
if (!System.IO.File.Exists(srcPath)) {
Console.Write(srcPath+" does not exists.");
return;
}
var format = ImageFormat.Jpeg;
var extension = "jpg";
var dstPath = srcPath;
if(args.Length > 1) {
dstPath = args[1];
if(args.Length > 2) {
var fmtStr = args[2];
if(fmtStr == "png") {
format = ImageFormat.Png;
extension = "png";
}
else if(fmtStr == "gif") {
format = ImageFormat.Gif;
extension = "gif";
}
else if(fmtStr == "tiff") {
format = ImageFormat.Tiff;
extension = "tiff";
}
else if(fmtStr == "bmp") {
format = ImageFormat.Bmp;
extension = "bmp";
}
}
}
else {
dstPath = System.IO.Path.GetDirectoryName(srcPath);
}
Image img = null;
try {
img = Image.FromFile(srcPath);
}
catch(Exception e) {
Console.WriteLine("Exception raised."+Environment.NewLine+e.Message);
return;
}
if (!ImageAnimator.CanAnimate(img)) {
Console.WriteLine("This is not animation gif.");
img.Save(dstPath + "/0001."+extension, format);
return;
}
// 等倍で再生する
bool isReady = false;
ImageAnimator.Animate(img, (Object o, EventArgs e)=>isReady = true);
var renderTarget = new Bitmap(img.Width, img.Height);
using(var g = Graphics.FromImage(renderTarget)) {
var guid = img.FrameDimensionsList[0];
var dimension = new System.Drawing.Imaging.FrameDimension(guid);
var end = img.GetFrameCount(dimension);
for (int i = 0; i < end; ++i) {
// Animator が次のフレームを準備できるまで待つ
while (!isReady) { System.Threading.Thread.Sleep(10); }
isReady = false;
g.DrawImage(img, 0, 0);
renderTarget.Save(dstPath + string.Format("/{0:0000}.{1}", i, extension), format);
ImageAnimator.UpdateFrames(img);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment