// GIF动图工具箱 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法(net48 自带 csc 可编译) // 功能:图片序列 → GIF 动图(自写 GIF89a 编码器 + 中位切分调色板 + LZW) // GIF → 逐帧 PNG 导出(自写 GIF 解码器,含 LZW 解码) // GIF 信息查看(尺寸/帧数/总时长/循环次数) // 边界:GIF 上限 256 色,真彩照片会有色阶(这是格式限制,不是压缩偷工); // 不做 GIF 压缩优化(不裁色板、不丢帧),保持所见即所得。 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class GifFrameInfo { public int Width, Height, DelayMs; } public static class GifOps { /* ───────────── 像素读取:一次 LockBits,之后全程 int[] ───────────── */ // GetPixel 是每像素一次托管调用,30 帧 800×600 会卡到十几秒; // LockBits + Marshal.Copy 按行搬,快一个量级。 public static int[] PixelsOf(Bitmap bmp) { int w = bmp.Width, h = bmp.Height; Bitmap src = bmp; Bitmap owned = null; if (bmp.PixelFormat != PixelFormat.Format32bppArgb) { owned = new Bitmap(w, h, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(owned)) { g.CompositingMode = CompositingMode.SourceCopy; g.DrawImageUnscaled(bmp, 0, 0); } src = owned; } int[] px = new int[w * h]; int[] row = new int[w]; BitmapData bd = src.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); try { for (int y = 0; y < h; y++) { Marshal.Copy(new IntPtr(bd.Scan0.ToInt64() + (long)y * bd.Stride), row, 0, w); int off = y * w; for (int x = 0; x < w; x++) px[off + x] = row[x]; // 0xAARRGGBB,透明要用 } } finally { src.UnlockBits(bd); if (owned != null) owned.Dispose(); } return px; } /* ───────────── 调色板:中位切分 ───────────── */ public static byte[] BuildPalette(int[] pixels, int maxColors, out int tableSize, out int colorCount) { Dictionary hist = new Dictionary(); for (int i = 0; i < pixels.Length; i++) { int pv = pixels[i]; if (((pv >> 24) & 0xFF) < 128) continue; // 全透明像素不占色板 int key = pv & 0xFFFFFF; int cnt; if (hist.TryGetValue(key, out cnt)) hist[key] = cnt + 1; else hist[key] = 1; } List colors = new List(hist.Keys); List weights = new List(hist.Count); for (int i = 0; i < colors.Count; i++) weights.Add(hist[colors[i]]); List palette = new List(); if (colors.Count <= maxColors) { palette.AddRange(colors); // 颜色本来就不够 256 → 原样保留,一点不丢 } else { List boxes = new List(); boxes.Add(new Box(colors, weights)); while (boxes.Count < maxColors) { int best = -1; double bestScore = -1; for (int i = 0; i < boxes.Count; i++) { if (boxes[i].Colors.Count < 2) continue; double score = boxes[i].Score(); if (score > bestScore) { bestScore = score; best = i; } } if (best < 0) break; Box b = boxes[best]; Box b1, b2; b.Split(out b1, out b2); boxes.RemoveAt(best); boxes.Add(b1); boxes.Add(b2); } foreach (Box b in boxes) palette.Add(b.Average()); } if (palette.Count == 0) palette.Add(0); colorCount = palette.Count; // 补齐到 2 的幂(GIF 色板长度必须是 2 的幂) int n = 2; while (n < palette.Count) n *= 2; if (n > 256) n = 256; while (palette.Count < n) palette.Add(palette[0]); tableSize = n; byte[] table = new byte[n * 3]; for (int i = 0; i < n; i++) { int c = palette[i % palette.Count]; table[i * 3] = (byte)((c >> 16) & 0xFF); table[i * 3 + 1] = (byte)((c >> 8) & 0xFF); table[i * 3 + 2] = (byte)(c & 0xFF); } return table; } /* 像素 → 索引(带 32K 缓存加速) */ public static byte[] MapPixels(int[] pixels, byte[] table, int tableSize, int clearIndex) { byte[] idx = new byte[pixels.Length]; short[] cache = new short[32768]; for (int i = 0; i < cache.Length; i++) cache[i] = -1; for (int i = 0; i < pixels.Length; i++) { int c = pixels[i]; if (clearIndex >= 0 && ((c >> 24) & 0xFF) < 128) { idx[i] = (byte)clearIndex; continue; } c &= 0xFFFFFF; int cr = (c >> 16) & 0xFF, cg = (c >> 8) & 0xFF, cb = c & 0xFF; int ck = ((cr >> 3) << 10) | ((cg >> 3) << 5) | (cb >> 3); short hit = cache[ck]; int best; if (hit >= 0) { best = hit; } else { int bestDist = int.MaxValue; best = 0; for (int t = 0; t < tableSize; t++) { int dr = cr - table[t * 3]; int dg = cg - table[t * 3 + 1]; int db = cb - table[t * 3 + 2]; int d = dr * dr + dg * dg + db * db; if (d < bestDist) { bestDist = d; best = t; if (d == 0) break; } } cache[ck] = (short)best; } idx[i] = (byte)best; } return idx; } /* ───────────── LZW 编码(GIF 变体,LSB 先出) ───────────── */ public static List LzwEncode(byte[] indices, int minCodeSize) { List outBytes = new List(); int clearCode = 1 << minCodeSize; int endCode = clearCode + 1; int codeSize = minCodeSize + 1; Dictionary dict = new Dictionary(); int nextCode = clearCode + 2; List packed = new List(); int[] st = new int[2]; // st[0]=bitBuf st[1]=bitCount EmitCode(packed, clearCode, codeSize, st); int prefix = indices[0]; for (int i = 1; i < indices.Length; i++) { int k = indices[i]; int key = (prefix << 8) | k; int found; if (dict.TryGetValue(key, out found)) { prefix = found; } else { EmitCode(packed, prefix, codeSize, st); dict[key] = nextCode; nextCode++; // 编码端比解码端早一步建表,所以码长要在 "多出一位" 之后才加宽, // 否则会比标准解码器(PIL/浏览器/看图软件)早一码换宽度,整段错位 if (nextCode > (1 << codeSize) && codeSize < 12) codeSize++; if (nextCode >= 4096) { EmitCode(packed, clearCode, codeSize, st); dict.Clear(); nextCode = clearCode + 2; codeSize = minCodeSize + 1; } prefix = k; } } EmitCode(packed, prefix, codeSize, st); EmitCode(packed, endCode, codeSize, st); if (st[1] > 0) packed.Add((byte)(st[0] & 0xFF)); // 切成 255 字节子块 for (int i = 0; i < packed.Count; i += 255) { int n = Math.Min(255, packed.Count - i); outBytes.Add((byte)n); for (int j = 0; j < n; j++) outBytes.Add(packed[i + j]); } outBytes.Add(0); return outBytes; } static void EmitCode(List packed, int code, int codeSize, int[] st) { st[0] |= code << st[1]; st[1] += codeSize; while (st[1] >= 8) { packed.Add((byte)(st[0] & 0xFF)); st[0] >>= 8; st[1] -= 8; } } /* ───────────── LZW 解码 ───────────── */ public static byte[] LzwDecode(byte[] data, int minCodeSize, int pixelCount) { int clearCode = 1 << minCodeSize; int endCode = clearCode + 1; int codeSize = minCodeSize + 1; List dict = new List(); for (int i = 0; i < clearCode; i++) dict.Add(new byte[] { (byte)i }); dict.Add(null); // clear dict.Add(null); // end List outBytes = new List(pixelCount); int bitPos = 0; int old = -1; while (true) { int code = ReadCode(data, ref bitPos, codeSize); if (code < 0) break; if (code == clearCode) { codeSize = minCodeSize + 1; dict.RemoveRange(clearCode + 2, dict.Count - clearCode - 2); old = -1; continue; } if (code == endCode) break; byte[] entry; if (old == -1) { if (code >= dict.Count || dict[code] == null) break; entry = dict[code]; outBytes.AddRange(entry); old = code; continue; } byte[] prev = dict[old]; if (code < dict.Count) { entry = dict[code]; } else if (code == dict.Count) { byte[] nw = new byte[prev.Length + 1]; Array.Copy(prev, nw, prev.Length); nw[prev.Length] = prev[0]; entry = nw; } else { break; // 数据损坏 } outBytes.AddRange(entry); byte[] added = new byte[prev.Length + 1]; Array.Copy(prev, added, prev.Length); added[prev.Length] = entry[0]; dict.Add(added); // 标准解码节奏:字典里"下一个空位"达到 1< pixelCount * 2 + 4096) break; // 防御异常数据 } return outBytes.ToArray(); } static int ReadCode(byte[] data, ref int bitPos, int codeSize) { if ((bitPos + codeSize) > data.Length * 8) return -1; int value = 0; for (int i = 0; i < codeSize; i++) { int bp = bitPos + i; int bit = (data[bp >> 3] >> (bp & 7)) & 1; value |= bit << i; } bitPos += codeSize; return value; } /* ───────────── 编码整份 GIF ───────────── */ // 逐帧流式处理:不再把所有帧都留在内存里,30 帧 1080p 也只占一帧的像素数组。 // 每帧优先带自己的局部色板(LCT),只有和全局色板完全相同时才复用以省体积—— // 硬套一套全局色板会给不同场景的帧串色(实测均值误差 1 → 10,0~255 刻度)。 public static void EncodeGif(string[] imagePaths, string outPath, int delayMs, int loopCount, int maxWidth, out int frames, out int width, out int height) { if (imagePaths == null || imagePaths.Length == 0) throw new ArgumentException("没有可用的图片"); frames = imagePaths.Length; width = 0; height = 0; int delayCs = Math.Max(2, (int)Math.Round(delayMs / 10.0)); // GIF 单位 1/100 秒 byte[] gct = null; int gctSize = 0; int gctClear = -1; using (FileStream fs = new FileStream(outPath, FileMode.Create, FileAccess.Write)) { for (int i = 0; i < imagePaths.Length; i++) { Bitmap bmp = LoadFitted(imagePaths[i], maxWidth, width, height); try { if (i == 0) { width = bmp.Width; height = bmp.Height; } int[] px = PixelsOf(bmp); bool hasClear = false; for (int k = 0; k < px.Length; k++) { if (((px[k] >> 24) & 0xFF) < 128) { hasClear = true; break; } } int ts, colors; // 有透明像素时只留 255 色,多出来的那一格当透明索引 byte[] table = BuildPalette(px, hasClear ? 255 : 256, out ts, out colors); int clearIndex = hasClear ? colors : -1; byte[] useTable = table; int useSize = ts; int useClear = clearIndex; bool lct = false; if (i == 0) { gct = table; gctSize = ts; gctClear = clearIndex; } else if (SameTable(table, gct) && clearIndex == gctClear) { useTable = gct; useSize = gctSize; } else { lct = true; } int useBits = 1; while ((1 << useBits) < useSize) useBits++; if (i == 0) { // 文件头 + 逻辑屏幕描述符 + 全局色板 WriteAscii(fs, "GIF89a"); WriteShort(fs, width); WriteShort(fs, height); fs.WriteByte((byte)(0x80 | (useBits - 1))); // 有全局色板 fs.WriteByte(0); // 背景色索引 fs.WriteByte(0); // 像素宽高比 fs.Write(gct, 0, gct.Length); // 循环扩展(NETSCAPE2.0) fs.WriteByte(0x21); fs.WriteByte(0xFF); fs.WriteByte(0x0B); WriteAscii(fs, "NETSCAPE2.0"); fs.WriteByte(0x03); fs.WriteByte(0x01); WriteShort(fs, loopCount); fs.WriteByte(0x00); } // 图形控制扩展(每帧延时;有透明像素时带上透明索引) fs.WriteByte(0x21); fs.WriteByte(0xF9); fs.WriteByte(0x04); // 有透明的动图必须每帧「恢复背景」(2),否则上一帧会从透明处透出来叠成一团影子 fs.WriteByte((byte)(useClear >= 0 ? 0x09 : 0x04)); WriteShort(fs, delayCs); fs.WriteByte((byte)(useClear >= 0 ? useClear : 0)); fs.WriteByte(0x00); // 块结束 // 图像描述符 fs.WriteByte(0x2C); WriteShort(fs, 0); WriteShort(fs, 0); WriteShort(fs, width); WriteShort(fs, height); if (lct) { fs.WriteByte((byte)(0x80 | (useBits - 1))); // 有局部色板、非交错 fs.Write(useTable, 0, useTable.Length); } else { fs.WriteByte(0x00); // 无局部色板、非交错 } byte[] idx = MapPixels(px, useTable, useSize, useClear); int minCode = Math.Max(2, useBits); fs.WriteByte((byte)minCode); List data = LzwEncode(idx, minCode); fs.Write(data.ToArray(), 0, data.Count); } finally { bmp.Dispose(); } } fs.WriteByte(0x3B); // Trailer } } /* 载入并按目标尺寸/最大宽度归一化 */ static Bitmap LoadFitted(string path, int maxWidth, int targetW, int targetH) { Bitmap b = new Bitmap(path); if (maxWidth > 0 && b.Width > maxWidth) { int nh = Math.Max(1, (int)Math.Round((double)b.Height * maxWidth / b.Width)); Bitmap scaled = new Bitmap(maxWidth, nh, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(scaled)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(b, 0, 0, maxWidth, nh); } b.Dispose(); b = scaled; } if (targetW > 0 && (b.Width != targetW || b.Height != targetH)) { Bitmap fit = new Bitmap(targetW, targetH, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(fit)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(b, new Rectangle(0, 0, targetW, targetH)); } b.Dispose(); b = fit; } return b; } static bool SameTable(byte[] a, byte[] b) { if (a == null || b == null || a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) if (a[i] != b[i]) return false; return true; } static void WriteAscii(Stream s, string text) { byte[] b = Encoding.ASCII.GetBytes(text); s.Write(b, 0, b.Length); } static void WriteShort(Stream s, int v) { s.WriteByte((byte)(v & 0xFF)); s.WriteByte((byte)((v >> 8) & 0xFF)); } static int ReadShort(byte[] d, int pos) { return d[pos] | (d[pos + 1] << 8); } /* ───────────── 读取 GIF 信息 + 拆帧 ───────────── */ public static List ReadInfo(byte[] gif) { List list = new List(); int pos = 6; // 跳过 GIF89a int w = ReadShort(gif, pos); int h = ReadShort(gif, pos + 2); int packed = gif[pos + 4]; pos += 7; bool hasGct = (packed & 0x80) != 0; int gctSize = hasGct ? (2 << (packed & 0x07)) : 0; if (hasGct) pos += gctSize * 3; int delay = 100; // 默认 100ms while (pos < gif.Length) { byte b = gif[pos]; if (b == 0x3B) break; if (b == 0x21) { byte label = gif[pos + 1]; pos += 2; if (label == 0xF9) // 图形控制 { int blockSize = gif[pos]; delay = ReadShort(gif, pos + 2) * 10; pos += blockSize + 1; pos = SkipSubBlocks(gif, pos); } else { pos = SkipSubBlocks(gif, pos); } continue; } if (b == 0x2C) { int fw = ReadShort(gif, pos + 5); int fh = ReadShort(gif, pos + 7); int p2 = gif[pos + 9]; pos += 10; if ((p2 & 0x80) != 0) pos += (2 << (p2 & 0x07)) * 3; pos++; // minCodeSize pos = SkipSubBlocks(gif, pos); GifFrameInfo info = new GifFrameInfo(); info.Width = fw; info.Height = fh; info.DelayMs = delay; list.Add(info); continue; } pos++; } if (list.Count == 0) { GifFrameInfo info = new GifFrameInfo(); info.Width = w; info.Height = h; info.DelayMs = 0; list.Add(info); } return list; } static int SkipSubBlocks(byte[] d, int pos) { while (pos < d.Length) { int n = d[pos]; pos++; if (n == 0) break; pos += n; } return pos; } /* 拆帧:按画布合成后用 PNG 写出(保留透明),返回写出的文件列表 真实世界的 GIF 多是"帧矩形 + 局部补丁 + 透明色 + 处置方式", 只把每帧自己的小矩形存成 PNG,用户拿到的就是一堆碎片,所以必须合成。 */ public static List ExtractFrames(string gifPath, string dir) { byte[] gif = File.ReadAllBytes(gifPath); List files = new List(); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); int pos = 6; int screenW = ReadShort(gif, pos); int screenH = ReadShort(gif, pos + 2); int packed = gif[pos + 4]; pos += 7; bool hasGct = (packed & 0x80) != 0; int gctSize = hasGct ? (2 << (packed & 0x07)) : 0; byte[] gct = null; if (hasGct) { gct = new byte[gctSize * 3]; Array.Copy(gif, pos, gct, 0, gctSize * 3); pos += gctSize * 3; } int canvasW = Math.Max(1, screenW); int canvasH = Math.Max(1, screenH); int[] canvas = new int[canvasW * canvasH]; // 0 = 全透明 int[] backup = null; // 处置方式 3 用 int frameIndex = 0; int pendingDisposal = 0; bool pendingTransparent = false; int pendingTransIndex = 0; while (pos < gif.Length) { byte b = gif[pos]; if (b == 0x3B) break; if (b == 0x21) { byte label = gif[pos + 1]; pos += 2; if (label == 0xF9 && pos + 3 < gif.Length) { int blockSize = gif[pos]; int flag = gif[pos + 1]; pendingDisposal = (flag >> 2) & 0x07; pendingTransparent = (flag & 0x01) != 0; pendingTransIndex = pos + 4 < gif.Length ? gif[pos + 4] : 0; pos += blockSize + 1; pos = SkipSubBlocks(gif, pos); } else { pos = SkipSubBlocks(gif, pos); } continue; } if (b != 0x2C) { pos++; continue; } int left = ReadShort(gif, pos + 1); int top = ReadShort(gif, pos + 3); int fw = ReadShort(gif, pos + 5); int fh = ReadShort(gif, pos + 7); int p2 = gif[pos + 9]; bool interlaced = (p2 & 0x40) != 0; pos += 10; byte[] palette = gct; if ((p2 & 0x80) != 0) { int palSize = 2 << (p2 & 0x07); palette = new byte[palSize * 3]; Array.Copy(gif, pos, palette, 0, palSize * 3); pos += palSize * 3; } int minCode = gif[pos]; pos++; List chunks = new List(); while (pos < gif.Length) { int n = gif[pos]; pos++; if (n == 0) break; for (int i = 0; i < n; i++) chunks.Add(gif[pos + i]); pos += n; } byte[] idx = LzwDecode(chunks.ToArray(), minCode, fw * fh); // 处置方式 3(恢复上一帧)需要先存一份 if (pendingDisposal == 3) backup = (int[])canvas.Clone(); int[] rowOffsets = BuildRowOffsets(fh, interlaced); for (int yy = 0; yy < fh; yy++) { int cy = top + yy; if (cy < 0 || cy >= canvasH) continue; int srcRow = rowOffsets[yy]; for (int x = 0; x < fw; x++) { int cx = left + x; if (cx < 0 || cx >= canvasW) continue; int p = srcRow * fw + x; if (p >= idx.Length) continue; int ci = idx[p]; if (pendingTransparent && ci == pendingTransIndex) continue; // 透出底下的内容 int off = ci * 3; int r = 0, g = 0, bl = 0; if (palette != null && off + 2 < palette.Length) { r = palette[off]; g = palette[off + 1]; bl = palette[off + 2]; } canvas[cy * canvasW + cx] = unchecked((int)0xFF000000) | (r << 16) | (g << 8) | bl; } } frameIndex++; string file = Path.Combine(dir, "frame_" + frameIndex.ToString("000") + ".png"); SaveCanvas(canvas, canvasW, canvasH, file); files.Add(file); if (pendingDisposal == 2) { // 恢复背景:把这一帧占的矩形擦成透明 for (int yy = 0; yy < fh; yy++) { int cy = top + yy; if (cy < 0 || cy >= canvasH) continue; for (int x = 0; x < fw; x++) { int cx = left + x; if (cx < 0 || cx >= canvasW) continue; canvas[cy * canvasW + cx] = 0; } } } else if (pendingDisposal == 3 && backup != null) { canvas = backup; backup = null; } pendingDisposal = 0; pendingTransparent = false; } return files; } static void SaveCanvas(int[] canvas, int w, int h, string file) { using (Bitmap bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb)) { BitmapData bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); try { int[] row = new int[w]; for (int y = 0; y < h; y++) { Array.Copy(canvas, y * w, row, 0, w); Marshal.Copy(row, 0, new IntPtr(bd.Scan0.ToInt64() + (long)y * bd.Stride), w); } } finally { bmp.UnlockBits(bd); } bmp.Save(file, ImageFormat.Png); } } /* 交错 GIF 的行顺序:返回「输出第 i 行该读传输流里的第几行」 (非交错是恒等映射;交错按 0/8、4/8、2/4、1/2 四趟发,读回来要反过来对) */ static int[] BuildRowOffsets(int h, bool interlaced) { int[] offsets = new int[h]; if (!interlaced) { for (int i = 0; i < h; i++) offsets[i] = i; return offsets; } int[][] passes = new int[][] { new int[] { 0, 8 }, new int[] { 4, 8 }, new int[] { 2, 4 }, new int[] { 1, 2 } }; int pos = 0; for (int p = 0; p < passes.Length; p++) { for (int y = passes[p][0]; y < h; y += passes[p][1]) { offsets[y] = pos; pos++; } } return offsets; } /* 自然排序:图2 排在 图10 前 */ public static int NaturalCompare(string a, string b) { string fa = Path.GetFileName(a), fb = Path.GetFileName(b); int i = 0, j = 0; while (i < fa.Length && j < fb.Length) { if (char.IsDigit(fa[i]) && char.IsDigit(fb[j])) { long va = 0, vb = 0; while (i < fa.Length && char.IsDigit(fa[i])) { va = va * 10 + (fa[i] - '0'); i++; } while (j < fb.Length && char.IsDigit(fb[j])) { vb = vb * 10 + (fb[j] - '0'); j++; } if (va != vb) return va < vb ? -1 : 1; } else { if (fa[i] != fb[j]) return fa[i] < fb[j] ? -1 : 1; i++; j++; } } return (fa.Length - i) - (fb.Length - j); } } /* 中位切分用的色块 */ public class Box { public List Colors; public List Weights; public Box(List colors, List weights) { Colors = colors; Weights = weights; } public double Score() { int minR = 255, maxR = 0, minG = 255, maxG = 0, minB = 255, maxB = 0; for (int i = 0; i < Colors.Count; i++) { int c = Colors[i]; int r = (c >> 16) & 0xFF, g = (c >> 8) & 0xFF, b = c & 0xFF; if (r < minR) minR = r; if (r > maxR) maxR = r; if (g < minG) minG = g; if (g > maxG) maxG = g; if (b < minB) minB = b; if (b > maxB) maxB = b; } int dr = maxR - minR, dg = maxG - minG, db = maxB - minB; return (double)(dr * dr + dg * dg + db * db) * Colors.Count; } public void Split(out Box a, out Box b) { int minR = 255, maxR = 0, minG = 255, maxG = 0, minB = 255, maxB = 0; for (int i = 0; i < Colors.Count; i++) { int c = Colors[i]; int r = (c >> 16) & 0xFF, g = (c >> 8) & 0xFF, bl = c & 0xFF; if (r < minR) minR = r; if (r > maxR) maxR = r; if (g < minG) minG = g; if (g > maxG) maxG = g; if (bl < minB) minB = bl; if (bl > maxB) maxB = bl; } int dr = maxR - minR, dg = maxG - minG, db = maxB - minB; int axis = 0; if (dg >= dr && dg >= db) axis = 1; else if (db >= dr && db >= dg) axis = 2; // 按主轴排序 List> pairs = new List>(); for (int i = 0; i < Colors.Count; i++) pairs.Add(new KeyValuePair(Colors[i], Weights[i])); pairs.Sort(delegate (KeyValuePair x, KeyValuePair y) { int a1 = Channel(x.Key, axis), b1 = Channel(y.Key, axis); return a1.CompareTo(b1); }); int mid = pairs.Count / 2; if (mid < 1) mid = 1; List ca = new List(), wa = new List(); List cb = new List(), wb = new List(); for (int i = 0; i < pairs.Count; i++) { if (i < mid) { ca.Add(pairs[i].Key); wa.Add(pairs[i].Value); } else { cb.Add(pairs[i].Key); wb.Add(pairs[i].Value); } } a = new Box(ca, wa); b = new Box(cb, wb); } static int Channel(int c, int axis) { if (axis == 0) return (c >> 16) & 0xFF; if (axis == 1) return (c >> 8) & 0xFF; return c & 0xFF; } public int Average() { long r = 0, g = 0, b = 0, w = 0; for (int i = 0; i < Colors.Count; i++) { int c = Colors[i], wt = Weights[i]; r += ((c >> 16) & 0xFF) * wt; g += ((c >> 8) & 0xFF) * wt; b += (c & 0xFF) * wt; w += wt; } if (w == 0) return 0; return (int)((r / w) << 16 | (g / w) << 8 | (b / w)); } } public partial class GifForm : Form { private ComboBox cmbDelay, cmbLoop, cmbWidth; private Button btnMake, btnSplit, btnInfo; private TextBox txtLog; private Label lblStatus; internal string outDirOverride; // 自测用:输出目录重定向 public GifForm() { InitUi(); } private void InitUi() { this.Text = "GIF动图工具箱 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(720, 500); this.MinimumSize = new Size(720, 500); int x = 16, y = 14; Label t = new Label(); t.Text = "图片序列合成 GIF 动图 / GIF 拆成逐帧 PNG / 查看动图信息;全程本地处理,原文件不动"; t.Location = new Point(x, y); t.AutoSize = true; t.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(t); y += 36; Label l1 = new Label(); l1.Text = "每帧时长"; l1.Location = new Point(x, y + 6); l1.AutoSize = true; this.Controls.Add(l1); cmbDelay = new ComboBox(); cmbDelay.DropDownStyle = ComboBoxStyle.DropDownList; cmbDelay.Items.AddRange(new object[] { "100 毫秒", "200 毫秒", "300 毫秒", "500 毫秒", "1000 毫秒" }); cmbDelay.SelectedIndex = 1; cmbDelay.Location = new Point(x + 66, y + 2); cmbDelay.Size = new Size(110, 26); this.Controls.Add(cmbDelay); Label l2 = new Label(); l2.Text = "循环"; l2.Location = new Point(x + 190, y + 6); l2.AutoSize = true; this.Controls.Add(l2); cmbLoop = new ComboBox(); cmbLoop.DropDownStyle = ComboBoxStyle.DropDownList; cmbLoop.Items.AddRange(new object[] { "无限循环", "播 1 次", "播 3 次" }); cmbLoop.SelectedIndex = 0; cmbLoop.Location = new Point(x + 226, y + 2); cmbLoop.Size = new Size(100, 26); this.Controls.Add(cmbLoop); Label l3 = new Label(); l3.Text = "宽度"; l3.Location = new Point(x + 342, y + 6); l3.AutoSize = true; this.Controls.Add(l3); cmbWidth = new ComboBox(); cmbWidth.DropDownStyle = ComboBoxStyle.DropDownList; cmbWidth.Items.AddRange(new object[] { "保持原宽", "320 px", "480 px", "640 px" }); cmbWidth.SelectedIndex = 0; cmbWidth.Location = new Point(x + 378, y + 2); cmbWidth.Size = new Size(110, 26); this.Controls.Add(cmbWidth); y += 44; btnMake = new Button(); btnMake.Text = "选图片合成 GIF…"; btnMake.Location = new Point(x, y); btnMake.Size = new Size(170, 38); btnMake.BackColor = Color.FromArgb(0, 145, 88); btnMake.ForeColor = Color.White; btnMake.FlatStyle = FlatStyle.Flat; btnMake.Click += new EventHandler(MakeClick); this.Controls.Add(btnMake); btnSplit = new Button(); btnSplit.Text = "选 GIF 拆帧…"; btnSplit.Location = new Point(x + 186, y); btnSplit.Size = new Size(150, 38); btnSplit.Click += new EventHandler(SplitClick); this.Controls.Add(btnSplit); btnInfo = new Button(); btnInfo.Text = "查看 GIF 信息…"; btnInfo.Location = new Point(x + 352, y); btnInfo.Size = new Size(150, 38); btnInfo.Click += new EventHandler(InfoClick); this.Controls.Add(btnInfo); y += 52; txtLog = new TextBox(); txtLog.Multiline = true; txtLog.ScrollBars = ScrollBars.Vertical; txtLog.ReadOnly = true; txtLog.Location = new Point(x, y); txtLog.Size = new Size(688, 250); this.Controls.Add(txtLog); y += 262; lblStatus = new Label(); lblStatus.Text = "提示:GIF 最多 256 色(照片会有轻微色阶);PNG 的透明区域会保留;输出到「图片\\GIF动图」。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = Color.FromArgb(120, 130, 124); this.Controls.Add(lblStatus); Log("点下面的按钮开始:合成 GIF / 拆帧 / 看信息"); Log("支持 PNG、JPG、BMP、GIF(GIF 取第一帧);PNG 的透明区域会保留"); Log("输出目录:" + OutDir()); Log(""); } internal static string OutDir() { string pic = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); if (string.IsNullOrEmpty(pic) || !Directory.Exists(pic)) pic = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); return Path.Combine(pic, "GIF动图"); } private void Log(string line) { txtLog.AppendText(line + "\r\n"); } private void MakeClick(object sender, EventArgs e) { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "选择图片(可多选,按文件名自然顺序合成)"; dlg.Multiselect = true; dlg.Filter = "图片 (*.png;*.jpg;*.jpeg;*.bmp)|*.png;*.jpg;*.jpeg;*.bmp"; if (dlg.ShowDialog(this) != DialogResult.OK) return; MakeGif(dlg.FileNames); } } internal string MakeGif(string[] files) { Array.Sort(files, new Comparison(GifOps.NaturalCompare)); int delay = 100; switch (cmbDelay.SelectedIndex) { case 1: delay = 200; break; case 2: delay = 300; break; case 3: delay = 500; break; case 4: delay = 1000; break; } int loop = cmbLoop.SelectedIndex == 0 ? 0 : (cmbLoop.SelectedIndex == 1 ? 1 : 3); int maxW = cmbWidth.SelectedIndex == 0 ? 0 : (cmbWidth.SelectedIndex == 1 ? 320 : (cmbWidth.SelectedIndex == 2 ? 480 : 640)); string dir = outDirOverride != null ? outDirOverride : OutDir(); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string outPath = Path.Combine(dir, "动图_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".gif"); int frames, w, h; try { GifOps.EncodeGif(files, outPath, delay, loop, maxW, out frames, out w, out h); } catch (Exception ex) { Log("合成失败:" + ex.Message); return ""; } long size = new FileInfo(outPath).Length; Log("已合成:" + outPath); Log(" 帧数 " + frames + " · 尺寸 " + w + "x" + h + " · 每帧 " + delay + "ms · 体积 " + (size / 1024) + "KB"); Log(""); return outPath; } private void SplitClick(object sender, EventArgs e) { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "选择 GIF 文件"; dlg.Filter = "GIF 动图 (*.gif)|*.gif"; if (dlg.ShowDialog(this) != DialogResult.OK) return; SplitGif(dlg.FileName); } } internal List SplitGif(string gifPath) { string dir = outDirOverride != null ? outDirOverride : OutDir(); string sub = Path.Combine(dir, Path.GetFileNameWithoutExtension(gifPath) + "_帧"); List files; try { files = GifOps.ExtractFrames(gifPath, sub); } catch (Exception ex) { Log("拆帧失败:" + ex.Message); return new List(); } Log("已拆出 " + files.Count + " 帧到:" + sub); Log(""); return files; } private void InfoClick(object sender, EventArgs e) { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "选择 GIF 文件"; dlg.Filter = "GIF 动图 (*.gif)|*.gif"; if (dlg.ShowDialog(this) != DialogResult.OK) return; Log(GifInfoText(dlg.FileName)); } } internal string GifInfoText(string gifPath) { byte[] data = File.ReadAllBytes(gifPath); List frames = GifOps.ReadInfo(data); int total = 0; int w = frames[0].Width, h = frames[0].Height; foreach (GifFrameInfo f in frames) total += (f.DelayMs <= 0 ? 100 : f.DelayMs); StringBuilder sb = new StringBuilder(); sb.AppendLine("文件:" + Path.GetFileName(gifPath)); sb.AppendLine("尺寸:" + w + " × " + h + " 帧数:" + frames.Count); sb.AppendLine("总时长:" + (total / 1000.0).ToString("0.0") + " 秒(每帧约 " + frames[0].DelayMs + "ms)"); sb.AppendLine("体积:" + (data.Length / 1024) + " KB"); return sb.ToString(); } internal string TestLog { get { return txtLog.Text; } } } // ───────────────────────── 自测 ───────────────────────── public static class GifSelfTest { static int _pass, _fail; static List _lines = new List(); /* 手拼一份 4x8 隔行 GIF:每行用自己的颜色索引,行序错位会被断言抓到 */ static byte[] BuildInterlacedGif() { int w = 4, h = 8; List b = new List(); b.AddRange(Encoding.ASCII.GetBytes("GIF89a")); b.Add((byte)w); b.Add(0); b.Add((byte)h); b.Add(0); b.Add(0x82); // 有全局色板,8 色 b.Add(0); b.Add(0); for (int i = 0; i < 8; i++) { b.Add((byte)(i * 30)); // R b.Add((byte)(255 - i * 30)); // G b.Add((byte)(i * 10)); // B } b.Add(0x21); b.Add(0xF9); b.Add(0x04); b.Add(0x04); b.Add(10); b.Add(0); b.Add(0); b.Add(0x00); b.Add(0x2C); b.Add(0); b.Add(0); b.Add(0); b.Add(0); b.Add((byte)w); b.Add(0); b.Add((byte)h); b.Add(0); b.Add(0x40); // 隔行 b.Add(0x03); // minCodeSize = 3(8 色) int[] order = new int[] { 0, 4, 2, 6, 1, 3, 5, 7 }; // 四个 pass 的传输顺序 byte[] idx = new byte[w * h]; for (int r = 0; r < order.Length; r++) for (int x = 0; x < w; x++) idx[r * w + x] = (byte)order[r]; b.AddRange(GifOps.LzwEncode(idx, 3)); b.Add(0x3B); return b.ToArray(); } /* 手拼一份 8x8 的两帧 GIF:第 1 帧整幅红,第 2 帧 4x4 绿色补丁贴在 (2,2) 且补丁左上角是透明色 → 拆帧应该得到「整幅红」和「红底 + 绿块」两张 8x8 图 */ static byte[] BuildRectGif() { List b = new List(); b.AddRange(Encoding.ASCII.GetBytes("GIF89a")); b.Add(8); b.Add(0); b.Add(8); b.Add(0); // 画布 8x8 b.Add(0x81); // 有全局色板,4 色 b.Add(0); b.Add(0); b.AddRange(new byte[] { 0, 0, 0, 255, 0, 0, 0, 255, 0, 255, 255, 255 }); byte[] full = new byte[64]; for (int i = 0; i < full.Length; i++) full[i] = 1; // 全红 AddRectFrame(b, 0, 0, 8, 8, 0x04, 0, full); // 处置方式 1,不透明 byte[] patch = new byte[16]; for (int i = 0; i < patch.Length; i++) patch[i] = 2; // 绿 patch[0] = 0; // 左上角用透明色 AddRectFrame(b, 2, 2, 4, 4, 0x05, 0, patch); // 处置方式 1 + 透明 b.Add(0x3B); return b.ToArray(); } static void AddRectFrame(List b, int left, int top, int w, int h, int gceFlag, int transIndex, byte[] idx) { b.Add(0x21); b.Add(0xF9); b.Add(0x04); b.Add((byte)gceFlag); b.Add(10); b.Add(0); // 延时 10/100 秒 b.Add((byte)transIndex); b.Add(0x00); b.Add(0x2C); b.Add((byte)(left & 0xFF)); b.Add((byte)((left >> 8) & 0xFF)); b.Add((byte)(top & 0xFF)); b.Add((byte)((top >> 8) & 0xFF)); b.Add((byte)(w & 0xFF)); b.Add((byte)((w >> 8) & 0xFF)); b.Add((byte)(h & 0xFF)); b.Add((byte)((h >> 8) & 0xFF)); b.Add(0x00); // 无局部色板、非交错 b.Add(0x02); // minCodeSize = 2(4 色) b.AddRange(GifOps.LzwEncode(idx, 2)); } static string Hex(List data) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.Count; i++) { if (i > 0) sb.Append(' '); sb.Append(data[i].ToString("X2")); } return sb.ToString(); } static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("GIF动图工具箱 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-gif-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // LZW 往返:小索引数组 byte[] src = new byte[] { 0, 1, 2, 1, 1, 3, 3, 2, 0, 0, 1, 2, 3, 3, 3, 0 }; List packed = GifOps.LzwEncode(src, 2); // 去掉子块长度/结束符,拼回连续字节 List raw = new List(); int p = 0; while (p < packed.Count) { int n = packed[p]; p++; if (n == 0) break; for (int i = 0; i < n; i++) raw.Add(packed[p + i]); p += n; } byte[] back = GifOps.LzwDecode(raw.ToArray(), 2, src.Length); bool same = back.Length >= src.Length; for (int i = 0; i < src.Length && same; i++) if (back[i] != src[i]) same = false; Check("LZW 往返一致", same, true); // 金标字节:这一段码流是「标准解码器(PIL / 浏览器 / 看图软件)能吃」的字节。 // 教训:编码端与解码端一起错时互通无阻,自测全绿、外部全炸——用固定字节钉死。 Check("LZW 码流与标准字节一致(16 像素)", Hex(raw), "44 14 31 23 60 B2 06 28"); // LZW 长序列(触发字典增长与码长提升) byte[] big = new byte[5000]; for (int i = 0; i < big.Length; i++) big[i] = (byte)((i * 7) % 16); List packed2 = GifOps.LzwEncode(big, 4); List raw2 = new List(); p = 0; while (p < packed2.Count) { int n = packed2[p]; p++; if (n == 0) break; for (int i = 0; i < n; i++) raw2.Add(packed2[p + i]); p += n; } byte[] back2 = GifOps.LzwDecode(raw2.ToArray(), 4, big.Length); bool same2 = back2.Length >= big.Length; for (int i = 0; i < big.Length && same2; i++) if (back2[i] != big[i]) same2 = false; Check("LZW 5000 字节往返", same2, true); // 中长序列金标:码长要在 8→9 位之间换一次,正好卡在当年出错的那条边界上 byte[] mid = new byte[200]; for (int i = 0; i < mid.Length; i++) mid[i] = (byte)(i % 8); List packed3 = GifOps.LzwEncode(mid, 4); List raw3 = new List(); p = 0; while (p < packed3.Count) { int n = packed3[p]; p++; if (n == 0) break; for (int i = 0; i < n; i++) raw3.Add(packed3[p + i]); p += n; } Check("LZW 码流与标准字节一致(200 像素)", Hex(raw3), "10 04 31 48 31 47 52 8B 75 BD D9 F4 75 22 17 6E A0 67 AA 69 D9 A2 24 7C 8E F3 EA C6 34 8B DB B2 5E BF B9 DB 6F 07 34 45 00"); // 造 3 张纯色小图 → 合成 GIF → 解码校验 Color[] colors = new Color[] { Color.Red, Color.Lime, Color.Blue }; string[] paths = new string[3]; for (int i = 0; i < 3; i++) { paths[i] = Path.Combine(baseDir, "img" + (i + 1) + ".png"); using (Bitmap b = new Bitmap(16, 16)) { using (Graphics g = Graphics.FromImage(b)) { g.Clear(colors[i]); } b.Save(paths[i], ImageFormat.Png); } } string gifPath = Path.Combine(baseDir, "out.gif"); int frames, w, h; GifOps.EncodeGif(paths, gifPath, 200, 0, 0, out frames, out w, out h); Check("GIF 已生成", File.Exists(gifPath) && new FileInfo(gifPath).Length > 100, true); Check("帧数", frames, 3); Check("尺寸", w + "x" + h, "16x16"); byte[] gifData = File.ReadAllBytes(gifPath); Check("文件头 GIF89a", Encoding.ASCII.GetString(gifData, 0, 6), "GIF89a"); Check("有文件尾 0x3B", gifData[gifData.Length - 1], 0x3B); List infos = GifOps.ReadInfo(gifData); Check("解析帧数", infos.Count, 3); Check("解析尺寸", infos[0].Width + "x" + infos[0].Height, "16x16"); Check("解析每帧时长", infos[0].DelayMs, 200); // 拆帧 → 每帧颜色应对应原图(允许 ±8 的量化误差) string frameDir = Path.Combine(baseDir, "frames"); List outs = GifOps.ExtractFrames(gifPath, frameDir); Check("拆出 3 帧", outs.Count, 3); for (int i = 0; i < outs.Count; i++) { using (Bitmap b = new Bitmap(outs[i])) { Color c = b.GetPixel(8, 8); bool close = Math.Abs(c.R - colors[i].R) <= 8 && Math.Abs(c.G - colors[i].G) <= 8 && Math.Abs(c.B - colors[i].B) <= 8; Check("第 " + (i + 1) + " 帧颜色正确", close, true); } } // GDI+ 独立解码才算数:自己解自己永远对得上,别家软件打不开就是白做 int gdiFrames = 0; bool gdiColorOk = true; using (FileStream gfs = new FileStream(gifPath, FileMode.Open, FileAccess.Read)) using (Image gi = Image.FromStream(gfs)) { FrameDimension fd = new FrameDimension(gi.FrameDimensionsList[0]); gdiFrames = gi.GetFrameCount(fd); for (int i = 0; i < gdiFrames && i < colors.Length; i++) { gi.SelectActiveFrame(fd, i); using (Bitmap fb = new Bitmap(gi)) { Color c2 = fb.GetPixel(8, 8); if (Math.Abs(c2.R - colors[i].R) > 8 || Math.Abs(c2.G - colors[i].G) > 8 || Math.Abs(c2.B - colors[i].B) > 8) gdiColorOk = false; } } } Check("GDI+ 能读出 3 帧", gdiFrames, 3); Check("GDI+ 读出的颜色正确", gdiColorOk, true); // 缩放:宽 8px 输出 string gifSmall = Path.Combine(baseDir, "small.gif"); GifOps.EncodeGif(paths, gifSmall, 100, 0, 8, out frames, out w, out h); Check("缩放后宽 8", w, 8); Check("缩放后高 8", h, 8); // 自然排序 Check("自然排序 2<10", GifOps.NaturalCompare("图2.png", "图10.png") < 0, true); Check("自然排序 1<2", GifOps.NaturalCompare("a1.png", "a2.png") < 0, true); // 真实 GIF 常见「整幅底帧 + 局部补丁帧 + 透明色」,手拼一份验证合成 string rectPath = Path.Combine(baseDir, "rect.gif"); File.WriteAllBytes(rectPath, BuildRectGif()); List rectOuts = GifOps.ExtractFrames(rectPath, Path.Combine(baseDir, "rectout")); Check("矩形帧拆出 2 帧", rectOuts.Count, 2); if (rectOuts.Count == 2) { using (Bitmap b0 = new Bitmap(rectOuts[0])) using (Bitmap b1 = new Bitmap(rectOuts[1])) { Check("矩形帧画布尺寸", b1.Width + "x" + b1.Height, "8x8"); Color c00 = b1.GetPixel(0, 0); // 补丁之外:保留底帧红色 Color c22 = b1.GetPixel(2, 2); // 补丁的透明像素:底下的红色透出来 Color c33 = b1.GetPixel(3, 3); // 补丁绿色 Check("补丁外保留底帧", c00.R > 200 && c00.G < 60, true); Check("透明像素透出底帧", c22.R > 200 && c22.G < 60, true); Check("补丁像素已覆盖", c33.G > 200 && c33.R < 60, true); Color d00 = b0.GetPixel(0, 0); Check("首帧整幅为红", d00.R > 200 && d00.G < 60, true); } } // 手工拼一份隔行 GIF:每行一个专用颜色,行序错了立刻能看出来 string interPath = Path.Combine(baseDir, "inter.gif"); File.WriteAllBytes(interPath, BuildInterlacedGif()); List interOuts = GifOps.ExtractFrames(interPath, Path.Combine(baseDir, "interout")); bool interOk = interOuts.Count == 1; if (interOk) { using (Bitmap b = new Bitmap(interOuts[0])) { if (b.Width != 4 || b.Height != 8) interOk = false; for (int y = 0; y < 8 && interOk; y++) { Color c = b.GetPixel(0, y); if (c.R != y * 30 || c.G != 255 - y * 30) interOk = false; } } } Check("隔行 GIF 行序正确", interOk, true); // Form 层 GifForm form = new GifForm(); form.outDirOverride = Path.Combine(baseDir, "formout"); Directory.CreateDirectory(form.outDirOverride); string made = form.MakeGif(paths); Check("Form 合成产物存在", made.Length > 0 && File.Exists(made), true); List split = form.SplitGif(made); Check("Form 拆帧数量", split.Count, 3); string infoText = form.GifInfoText(made); Check("Form 信息含帧数", infoText.Contains("帧数:3"), true); form.Dispose(); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { Directory.Delete(baseDir, true); } catch { } } _lines.Add(""); _lines.Add(_fail == 0 ? "结果:共 " + (_pass + _fail) + " 项,全部通过 ✓" : "结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-gif.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(GifSelfTest.Run(args.Length >= 2 ? args[1] : null)); } // 脚本/交叉验证用:--make out.gif 每帧毫秒 循环次数 最大宽度 图1 图2 ... if (args != null && args.Length >= 6 && args[0] == "--make") { string outPath = args[1]; int delay = int.Parse(args[2]); int loop = int.Parse(args[3]); int maxW = int.Parse(args[4]); string[] imgs = new string[args.Length - 5]; Array.Copy(args, 5, imgs, 0, imgs.Length); Array.Sort(imgs, new Comparison(GifOps.NaturalCompare)); int frames, w, h; GifOps.EncodeGif(imgs, outPath, delay, loop, maxW, out frames, out w, out h); Console.WriteLine("OK frames=" + frames + " size=" + w + "x" + h + " bytes=" + new FileInfo(outPath).Length); return; } // 脚本用:--extract in.gif 输出目录 if (args != null && args.Length >= 3 && args[0] == "--extract") { List outs = GifOps.ExtractFrames(args[1], args[2]); Console.WriteLine("OK frames=" + outs.Count); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new GifForm()); } } }