// 图片格式转换 - 绿色工具箱 // C# 5.0 语法,零依赖。批量转换 jpg/png/bmp/gif/tiff/emf // 注意:System.Drawing 不支持 WebP 输入输出(页面会注明) using System; using System.Text; using System.ComponentModel; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; namespace GreenToolbox { public class ImageConvertToolForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_PANEL = Color.FromArgb(245, 249, 246); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private TextBox txtFolder; private ComboBox cmbFormat; private Button btnRun; private ProgressBar progress; private Label lblStatus; private BackgroundWorker worker; private static readonly string[] FORMATS = new string[] { "jpg", "png", "bmp", "gif", "tiff", "emf" }; public ImageConvertToolForm() { InitUi(); worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += new DoWorkEventHandler(Work); worker.ProgressChanged += new ProgressChangedEventHandler(Prog); worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Done); } private void InitUi() { this.Text = "图片格式转换 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(620, 300); this.MinimumSize = new Size(560, 280); this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 20, y = 16; Label l0 = new Label(); l0.Text = "选文件夹(或拖进来),批量转换格式,结果放在\"转换后\"子文件夹"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 32; txtFolder = new TextBox(); txtFolder.Location = new Point(x, y); txtFolder.Size = new Size(460, 26); txtFolder.ReadOnly = true; txtFolder.BackColor = COL_PANEL; this.Controls.Add(txtFolder); Button btnBrowse = new Button(); btnBrowse.Text = "浏览"; btnBrowse.Location = new Point(488, y - 1); btnBrowse.Size = new Size(110, 28); btnBrowse.FlatStyle = FlatStyle.Flat; btnBrowse.FlatAppearance.BorderColor = COL_GREEN; btnBrowse.ForeColor = Color.FromArgb(0, 110, 66); btnBrowse.Click += new EventHandler(BrowseClick); this.Controls.Add(btnBrowse); y += 44; Label lt = new Label(); lt.Text = "转为:"; lt.AutoSize = true; lt.Location = new Point(x, y + 5); this.Controls.Add(lt); cmbFormat = new ComboBox(); cmbFormat.DropDownStyle = ComboBoxStyle.DropDownList; foreach (string f in FORMATS) cmbFormat.Items.Add(f.ToUpper()); cmbFormat.SelectedIndex = 0; cmbFormat.Location = new Point(x + 48, y + 2); cmbFormat.Size = new Size(100, 26); this.Controls.Add(cmbFormat); Label ln = new Label(); ln.Text = "注:JPG 不支持透明;WebP 暂不支持(GDI+ 限制)"; ln.AutoSize = true; ln.ForeColor = COL_GRAY; ln.Location = new Point(x + 168, y + 7); this.Controls.Add(ln); y += 44; btnRun = new Button(); btnRun.Text = "开始转换"; btnRun.Location = new Point(x, y); btnRun.Size = new Size(120, 34); btnRun.BackColor = COL_GREEN; btnRun.ForeColor = Color.White; btnRun.FlatStyle = FlatStyle.Flat; btnRun.FlatAppearance.BorderSize = 0; btnRun.Click += new EventHandler(RunClick); this.Controls.Add(btnRun); y += 48; progress = new ProgressBar(); progress.Location = new Point(x, y); progress.Size = new Size(578, 8); this.Controls.Add(progress); y += 20; lblStatus = new Label(); lblStatus.Text = "不联网、不上传,全部在本机完成。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; this.Controls.Add(lblStatus); } private void OnDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void OnDragDrop(object sender, DragEventArgs e) { string[] f = (string[])e.Data.GetData(DataFormats.FileDrop); if (f != null && f.Length > 0 && Directory.Exists(f[0])) txtFolder.Text = f[0]; } private void BrowseClick(object sender, EventArgs e) { using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择要转换图片的文件夹"; if (d.ShowDialog() == DialogResult.OK) txtFolder.Text = d.SelectedPath; } } private ImageFormat FormatById(int id) { return ImageConvertOps.FormatById(id); } private void RunClick(object sender, EventArgs e) { if (txtFolder.Text.Length == 0 || !Directory.Exists(txtFolder.Text)) { lblStatus.Text = "请先选择文件夹。"; return; } if (worker.IsBusy) return; btnRun.Enabled = false; progress.Value = 0; worker.RunWorkerAsync(new object[] { txtFolder.Text, cmbFormat.SelectedIndex }); } private void Work(object sender, DoWorkEventArgs e) { object[] a = (object[])e.Argument; e.Result = ImageConvertOps.ConvertAll((string)a[0], (int)a[1], (BackgroundWorker)sender); } private void Prog(object sender, ProgressChangedEventArgs e) { progress.Value = e.ProgressPercentage; } private void Done(object sender, RunWorkerCompletedEventArgs e) { btnRun.Enabled = true; object[] r = (object[])e.Result; lblStatus.Text = "完成:转换 " + r[0] + " 张,跳过(已是目标格式)" + r[1] + " 张。结果在\"转换后\"子文件夹。"; } } // ── 与界面解耦的纯逻辑,--selftest 直接调这里 ───────────────────────── public static class ImageConvertOps { public static readonly string[] FORMATS = new string[] { "jpg", "png", "bmp", "gif", "tiff", "emf" }; public static ImageFormat FormatById(int id) { switch (FORMATS[id]) { case "jpg": return ImageFormat.Jpeg; case "png": return ImageFormat.Png; case "bmp": return ImageFormat.Bmp; case "gif": return ImageFormat.Gif; case "tiff": return ImageFormat.Tiff; default: return ImageFormat.Emf; } } // png/gif/tiff 保留透明通道;jpg/bmp 没有 alpha,必须先压白底,否则透明区会变黑 public static bool TargetKeepsAlpha(string target) { return target == "png" || target == "gif" || target == "tiff"; } public static Image Prepare(Image src, string target) { if (TargetKeepsAlpha(target) || !Image.IsAlphaPixelFormat(src.PixelFormat)) return src; Bitmap flat = new Bitmap(src.Width, src.Height, PixelFormat.Format24bppRgb); using (Graphics g = Graphics.FromImage(flat)) { g.Clear(Color.White); g.DrawImage(src, 0, 0, src.Width, src.Height); } return flat; } // 同名文件不互相覆盖:a.png 和 a.gif 都转 jpg 时,第二个变成 a_2.jpg public static string UniquePath(string outDir, string name) { string p = Path.Combine(outDir, name); if (!File.Exists(p)) return p; string bn = Path.GetFileNameWithoutExtension(name); string ext = Path.GetExtension(name); for (int i = 2; i < 1000; i++) { p = Path.Combine(outDir, bn + "_" + i + ext); if (!File.Exists(p)) return p; } return p; } // 返回 object[] { 转换张数, 跳过张数, 失败日志 } public static object[] ConvertAll(string folder, int fmtId, BackgroundWorker bw) { string target = FORMATS[fmtId]; ImageFormat fmt = FormatById(fmtId); string[] exts = new string[] { "*.jpg", "*.jpeg", "*.png", "*.bmp", "*.gif", "*.tif", "*.tiff", "*.emf" }; List files = new List(); foreach (string pat in exts) foreach (string f in Directory.GetFiles(folder, pat, SearchOption.TopDirectoryOnly)) files.Add(f); string outDir = Path.Combine(folder, "转换后"); Directory.CreateDirectory(outDir); int idx = 0, ok = 0, skip = 0; StringBuilder log = new StringBuilder(); foreach (string f in files) { idx++; string cur = Path.GetExtension(f).TrimStart('.').ToLower(); bool same = (cur == target) || (target == "jpg" && cur == "jpeg") || (target == "tiff" && cur == "tif"); if (same) { skip++; } else { try { // 读进内存再解,避免一直锁着源文件(用户可能马上要删/改源目录) byte[] raw = File.ReadAllBytes(f); using (MemoryStream ms = new MemoryStream(raw)) using (Image src = Image.FromStream(ms)) { string outPath = UniquePath(outDir, Path.GetFileNameWithoutExtension(f) + "." + target); Image ready = Prepare(src, target); try { ready.Save(outPath, fmt); } finally { if (!object.ReferenceEquals(ready, src)) ready.Dispose(); } } ok++; } catch (Exception ex) { log.AppendLine(Path.GetFileName(f) + " 失败: " + ex.Message); } } if (bw != null && bw.WorkerReportsProgress && files.Count > 0) bw.ReportProgress(idx * 100 / files.Count); } return new object[] { ok, skip, log.ToString() }; } } // 命令行自测:不弹窗,纯逻辑跑一遍,退出码 0 = 全过,1 = 有失败 public static class SelfTest { private static int _pass = 0; private static int _fail = 0; private static List _lines = new List(); private static string Esc(string s) { if (s == null) return ""; if (s.Length > 90) s = s.Substring(0, 90) + "…"; return s.Replace("\r", "\\r").Replace("\n", "\\n"); } private static void Check(string name, string got, string want) { if (got == null) got = ""; if (want == null) want = ""; if (got == want) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " 期望[" + Esc(want) + "] 实际[" + Esc(got) + "]"); } } private static void CheckInt(string name, int got, int want) { Check(name, got.ToString(), want.ToString()); } private static string GuidOf(ImageFormat f) { return f.Guid.ToString(); } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-imgconvert-selftest"); string work = Path.Combine(dir, "src"); try { Directory.CreateDirectory(dir); _lines.Add("图片格式转换 自测(" + dir + ")"); // ── 格式表 ── CheckInt("格式表 6 种", ImageConvertOps.FORMATS.Length, 6); Check("0 号是 JPEG", GuidOf(ImageConvertOps.FormatById(0)), GuidOf(ImageFormat.Jpeg)); Check("1 号是 PNG", GuidOf(ImageConvertOps.FormatById(1)), GuidOf(ImageFormat.Png)); Check("2 号是 BMP", GuidOf(ImageConvertOps.FormatById(2)), GuidOf(ImageFormat.Bmp)); Check("3 号是 GIF", GuidOf(ImageConvertOps.FormatById(3)), GuidOf(ImageFormat.Gif)); // ── 透明通道判定 ── Check("jpg 不保留透明", ImageConvertOps.TargetKeepsAlpha("jpg") ? "yes" : "no", "no"); Check("bmp 不保留透明", ImageConvertOps.TargetKeepsAlpha("bmp") ? "yes" : "no", "no"); Check("png 保留透明", ImageConvertOps.TargetKeepsAlpha("png") ? "yes" : "no", "yes"); Check("gif 保留透明", ImageConvertOps.TargetKeepsAlpha("gif") ? "yes" : "no", "yes"); Check("tiff 保留透明", ImageConvertOps.TargetKeepsAlpha("tiff") ? "yes" : "no", "yes"); // ── 透明 PNG → JPG 必须压白底,不能变黑 ── Directory.CreateDirectory(work); using (Bitmap alpha = new Bitmap(100, 80, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(alpha)) { g.Clear(Color.Transparent); g.FillRectangle(Brushes.Red, 30, 20, 40, 40); using (Image ready = ImageConvertOps.Prepare(alpha, "jpg")) { Color corner = ((Bitmap)ready).GetPixel(2, 2); Check("透明区压成白色(不是黑块)", corner.R + "," + corner.G + "," + corner.B, "255,255,255"); Color mid = ((Bitmap)ready).GetPixel(50, 40); Check("不透明的主体颜色没变", (mid.R > 200 && mid.G < 60) ? "red" : mid.ToString(), "red"); } using (Image keep = ImageConvertOps.Prepare(alpha, "png")) { Check("转 PNG 时不做压底(保留透明)", object.ReferenceEquals(keep, alpha) ? "same" : "copied", "same"); } } // ── 真跑一轮:png + gif 撞名 + 已经是 jpg 的跳过 ── using (Bitmap a = new Bitmap(100, 80, PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(a)) { g.Clear(Color.Transparent); g.FillRectangle(Brushes.Red, 30, 20, 40, 40); a.Save(Path.Combine(work, "a.png"), ImageFormat.Png); } using (Bitmap c = new Bitmap(60, 40)) { c.Save(Path.Combine(work, "a.gif"), ImageFormat.Gif); } using (Bitmap b = new Bitmap(200, 120)) { b.Save(Path.Combine(work, "b.jpg"), ImageFormat.Jpeg); } object[] r = ImageConvertOps.ConvertAll(work, 0, null); CheckInt("转换 2 张", (int)r[0], 2); CheckInt("跳过 1 张(本身已是 jpg)", (int)r[1], 1); Check("没有失败", ((string)r[2]).Contains("失败") ? "error" : "clean", "clean"); string outDir = Path.Combine(work, "转换后"); Check("结果在「转换后」文件夹", Directory.Exists(outDir) ? "yes" : "no", "yes"); Check("同名不覆盖,第二个变成 a_2.jpg", File.Exists(Path.Combine(outDir, "a.jpg")) && File.Exists(Path.Combine(outDir, "a_2.jpg")) ? "both" : string.Join(",", Directory.GetFiles(outDir)), "both"); using (Image im = Image.FromFile(Path.Combine(outDir, "a.jpg"))) { Check("尺寸没被改动", im.Width + "x" + im.Height, "100x80"); Check("输出真的是 JPEG", im.RawFormat.Guid == ImageFormat.Jpeg.Guid ? "Jpeg" : "other", "Jpeg"); using (Bitmap probe = new Bitmap(im)) { Color c0 = probe.GetPixel(2, 2); Check("转出来的 jpg 边上也是白的(透明已压底)", c0.R + "," + c0.G + "," + c0.B, "255,255,255"); } } // ── 反向:jpg → png,再检查格式与尺寸 ── Directory.CreateDirectory(Path.Combine(dir, "src2")); string w2 = Path.Combine(dir, "src2"); using (Bitmap b = new Bitmap(200, 120)) { b.Save(Path.Combine(w2, "photo.jpg"), ImageFormat.Jpeg); } object[] r2 = ImageConvertOps.ConvertAll(w2, 1, null); CheckInt("jpg → png 转换 1 张", (int)r2[0], 1); CheckInt("没有可跳过的", (int)r2[1], 0); using (Image p = Image.FromFile(Path.Combine(w2, "转换后", "photo.png"))) { Check("输出真的是 PNG", p.RawFormat.Guid == ImageFormat.Png.Guid ? "Png" : "other", "Png"); Check("尺寸保持 200x120", p.Width + "x" + p.Height, "200x120"); } } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { if (Directory.Exists(work)) Directory.Delete(work, true); } catch { } try { string w2 = Path.Combine(dir, "src2"); if (Directory.Exists(w2)) Directory.Delete(w2, true); } catch { } } _lines.Add(""); if (_fail == 0) _lines.Add("结果:共 " + (_pass + _fail) + " 项,全部通过 ✓"); else _lines.Add("结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-imgconvert.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(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ImageConvertToolForm()); } } }