// 图片压缩 - 绿色工具箱 // C# 5.0 语法,零依赖(System.Drawing / GDI+ 为系统组件) // 功能:批量压缩 jpg/png/bmp,按质量压缩 + 可选限制最大宽度,输出到"压缩后"子文件夹 using System; using System.ComponentModel; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; using System.Threading; using System.Windows.Forms; namespace GreenToolbox { public class ImageCompressForm : 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 TrackBar barQuality; private Label lblQ; private TextBox txtMaxW; private Button btnRun; private ProgressBar progress; private Label lblStatus; private CheckBox chkOverwrite; private BackgroundWorker worker; public ImageCompressForm() { 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(660, 420); this.MinimumSize = new Size(600, 400); this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 20, y = 16; Label l0 = new Label(); l0.Text = "选文件夹(或拖进来),批量压缩 jpg/png/bmp,结果放在\"压缩后\"子文件夹"; 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(500, 26); txtFolder.ReadOnly = true; txtFolder.BackColor = COL_PANEL; this.Controls.Add(txtFolder); Button btnBrowse = new Button(); btnBrowse.Text = "浏览"; btnBrowse.Location = new Point(528, 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 lq = new Label(); lq.Text = "压缩质量:"; lq.AutoSize = true; lq.Location = new Point(x, y + 8); this.Controls.Add(lq); barQuality = new TrackBar(); barQuality.Minimum = 10; barQuality.Maximum = 100; barQuality.Value = 80; barQuality.Location = new Point(x + 78, y); barQuality.Size = new Size(400, 40); barQuality.ValueChanged += new EventHandler(delegate(object s, EventArgs e) { lblQ.Text = barQuality.Value + "(越小画质越低)"; }); this.Controls.Add(barQuality); lblQ = new Label(); lblQ.Text = "80(越小画质越低)"; lblQ.AutoSize = true; lblQ.ForeColor = COL_GRAY; lblQ.Location = new Point(x + 492, y + 12); this.Controls.Add(lblQ); y += 50; Label lw = new Label(); lw.Text = "最大宽度:"; lw.AutoSize = true; lw.Location = new Point(x, y + 5); this.Controls.Add(lw); txtMaxW = new TextBox(); txtMaxW.Location = new Point(x + 78, y + 2); txtMaxW.Size = new Size(80, 26); txtMaxW.Text = "0"; this.Controls.Add(txtMaxW); Label lw2 = new Label(); lw2.Text = "像素。0 = 不缩放;超宽图片等比缩小(如设 1920,适合发网页)"; lw2.AutoSize = true; lw2.ForeColor = COL_GRAY; lw2.Location = new Point(x + 168, y + 7); this.Controls.Add(lw2); y += 44; chkOverwrite = new CheckBox(); chkOverwrite.Text = "直接覆盖原文件(危险!默认关闭,输出到\"压缩后\"子文件夹)"; chkOverwrite.Location = new Point(x, y); chkOverwrite.AutoSize = true; this.Controls.Add(chkOverwrite); y += 36; 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(618, 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 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; int maxW = 0; int.TryParse(txtMaxW.Text, out maxW); worker.RunWorkerAsync(new object[] { txtFolder.Text, barQuality.Value, maxW, chkOverwrite.Checked }); } private static ImageCodecInfo GetJpegCodec() { return ImageOps.GetJpegCodec(); } private void Work(object sender, DoWorkEventArgs e) { object[] a = (object[])e.Argument; e.Result = ImageOps.Compress((string)a[0], (int)a[1], (int)a[2], (bool)a[3], (BackgroundWorker)sender); } private string Kb(long b) { return ImageOps.Kb(b); } private void Prog(object sender, ProgressChangedEventArgs e) { progress.Value = e.ProgressPercentage; if (e.UserState != null) lblStatus.Text = LastLine((string)e.UserState); } private string LastLine(string s) { string[] parts = s.Split('\n'); return parts[parts.Length - 1].Trim().Length > 0 ? parts[parts.Length - 1] : parts[parts.Length - 2]; } private void Done(object sender, RunWorkerCompletedEventArgs e) { btnRun.Enabled = true; object[] r = (object[])e.Result; long saved = (long)r[1]; lblStatus.Text = "完成:" + r[0] + " 张,共节省 " + Kb(saved) + (chkOverwrite.Checked ? "。覆盖模式下 PNG / BMP 保持原格式(只缩尺寸,不转 JPEG)。" : "。结果在\"压缩后\"子文件夹。"); } } // ── 与界面解耦的纯逻辑,--selftest 直接调这里 ───────────────────────── public static class ImageOps { public static ImageCodecInfo GetJpegCodec() { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo c in codecs) if (c.FormatID == ImageFormat.Jpeg.Guid) return c; return null; } public static string Kb(long b) { return (b / 1024.0).ToString("0.#") + " KB"; } // 等比缩到 maxW 宽;只缩不放(放大会糊);用 long 乘,避免 4 万像素宽时溢出 public static Size FitSize(int w, int h, int maxW) { if (maxW > 0 && w > maxW && w > 0) { h = (int)((long)h * maxW / w); if (h < 1) h = 1; w = maxW; } return new Size(w, h); } // 输出路径:默认一律 .jpg(PNG/BMP 只有转 JPEG 才明显变小);覆盖模式保留原名 public static string OutPath(string srcFile, string outDir, bool overwrite) { if (overwrite) return Path.Combine(outDir, Path.GetFileName(srcFile)); return Path.Combine(outDir, Path.GetFileNameWithoutExtension(srcFile) + ".jpg"); } // 编码器按扩展名选:内容必须和扩展名一致,否则会写出「.bmp 里装 PNG」这种坏文件 public static void SaveByExt(Image img, string path, int quality) { string ext = Path.GetExtension(path).ToLower(); if (ext == ".jpg" || ext == ".jpeg") { ImageCodecInfo jpeg = GetJpegCodec(); if (jpeg != null) { EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); img.Save(path, jpeg, ep); return; } img.Save(path, ImageFormat.Jpeg); return; } if (ext == ".png") { img.Save(path, ImageFormat.Png); return; } if (ext == ".bmp") { img.Save(path, ImageFormat.Bmp); return; } img.Save(path, ImageFormat.Png); } // 返回 object[] { 处理成功张数, 共节省字节, 明细日志 } public static object[] Compress(string folder, int quality, int maxW, bool overwrite, BackgroundWorker bw) { string[] exts = new string[] { "*.jpg", "*.jpeg", "*.png", "*.bmp" }; List files = new List(); foreach (string pat in exts) foreach (string f in Directory.GetFiles(folder, pat, SearchOption.TopDirectoryOnly)) files.Add(f); string outDir = overwrite ? folder : Path.Combine(folder, "压缩后"); if (!overwrite) Directory.CreateDirectory(outDir); long savedTotal = 0; int idx = 0, okCount = 0; StringBuilder log = new StringBuilder(); foreach (string f in files) { idx++; try { FileInfo fi = new FileInfo(f); string outPath = OutPath(f, outDir, overwrite); // 先读进内存:Image.FromFile 会一直锁着源文件,覆盖模式下再存回同一个路径 // 必然报「文件正被另一进程使用」。走 MemoryStream 就没有这个锁。 byte[] raw = File.ReadAllBytes(f); using (MemoryStream ms = new MemoryStream(raw)) using (Image img = Image.FromStream(ms)) { Size s = FitSize(img.Width, img.Height, maxW); using (Bitmap target = new Bitmap(s.Width, s.Height)) using (Graphics g = Graphics.FromImage(target)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(img, 0, 0, s.Width, s.Height); SaveByExt(target, outPath, quality); } } FileInfo fo = new FileInfo(outPath); long saved = fi.Length - fo.Length; if (saved > 0) savedTotal += saved; okCount++; log.AppendLine(fi.Name + ": " + Kb(fi.Length) + " → " + Kb(fo.Length)); } catch (Exception ex) { log.AppendLine(Path.GetFileName(f) + " 失败: " + ex.Message); } if (bw != null && bw.WorkerReportsProgress && files.Count > 0) bw.ReportProgress(idx * 100 / files.Count, log.ToString()); } return new object[] { okCount, savedTotal, 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 SizeText(Size s) { return s.Width + "x" + s.Height; } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-imgcompress-selftest"); string caseDir = Path.Combine(dir, "case1"); string owDir = Path.Combine(dir, "case2"); try { Directory.CreateDirectory(dir); _lines.Add("图片压缩 自测(" + dir + ")"); // ── 缩放算式 ── Check("4000x3000 收到 1600 宽", SizeText(ImageOps.FitSize(4000, 3000, 1600)), "1600x1200"); Check("本来就窄的图不放大小", SizeText(ImageOps.FitSize(1000, 800, 1600)), "1000x800"); Check("不设最大宽度时原样", SizeText(ImageOps.FitSize(1000, 800, 0)), "1000x800"); Check("4001x3000 收到 1600 宽(整除截断)", SizeText(ImageOps.FitSize(4001, 3000, 1600)), "1600x1199"); Check("超宽扁图不会缩成 0 高", SizeText(ImageOps.FitSize(3000, 1, 1600)), "1600x1"); // ── 体积文案 ── Check("0 字节", ImageOps.Kb(0), "0 KB"); Check("1536 字节", ImageOps.Kb(1536), "1.5 KB"); Check("100 KB", ImageOps.Kb(102400), "100 KB"); // ── 输出命名 ── // 输出目录是「传入的文件夹」下的子目录,这里传的是 caseDir,不是 dir string outc = Path.Combine(caseDir, "压缩后"); Check("非覆盖模式 PNG 也输出 .jpg", Path.GetFileName(ImageOps.OutPath("a/b/photo.PNG", outc, false)), "photo.jpg"); Check("覆盖模式保留原文件名", Path.GetFileName(ImageOps.OutPath("a/b/photo.PNG", outc, true)), "photo.PNG"); // ── 真跑一遍压缩 ── Directory.CreateDirectory(caseDir); using (Bitmap bmp = new Bitmap(2000, 1500)) using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.FromArgb(20, 90, 160)); g.FillEllipse(Brushes.Orange, 200, 200, 1200, 900); bmp.Save(Path.Combine(caseDir, "big.bmp"), ImageFormat.Bmp); } using (Bitmap png = new Bitmap(800, 600)) { png.Save(Path.Combine(caseDir, "small.png"), ImageFormat.Png); } using (Bitmap jpg = new Bitmap(1200, 900)) using (Graphics g2 = Graphics.FromImage(jpg)) { g2.Clear(Color.White); g2.FillRectangle(Brushes.SeaGreen, 100, 100, 600, 400); jpg.Save(Path.Combine(caseDir, "photo.jpg"), ImageFormat.Jpeg); } long bmpBytes = new FileInfo(Path.Combine(caseDir, "big.bmp")).Length; object[] r = ImageOps.Compress(caseDir, 60, 1000, false, null); CheckInt("三张全部处理成功", (int)r[0], 3); Check("生成了「压缩后」子文件夹", Directory.Exists(outc) ? "yes" : "no", "yes"); Check("输出的是 3 个 jpg", (Directory.GetFiles(outc, "*.jpg").Length).ToString(), "3"); using (Image im = Image.FromFile(Path.Combine(outc, "big.jpg"))) Check("大图按 1000 宽等比缩", SizeText(im.Size), "1000x750"); using (Image im2 = Image.FromFile(Path.Combine(outc, "small.jpg"))) Check("小图没被放大", SizeText(im2.Size), "800x600"); using (Image im3 = Image.FromFile(Path.Combine(outc, "photo.jpg"))) Check("1200 宽的 jpg 也缩到 1000", SizeText(im3.Size), "1000x750"); Check("BMP 转 JPEG 后确实变小了", new FileInfo(Path.Combine(outc, "big.jpg")).Length < bmpBytes ? "smaller" : "not-smaller", "smaller"); Check("返回的节省字节数大于 0", ((long)r[1] > 0) ? "positive" : "zero", "positive"); // ── 覆盖模式:扩展名和内容必须一致 ── Directory.CreateDirectory(owDir); using (Bitmap b = new Bitmap(600, 400)) { b.Save(Path.Combine(owDir, "notes.bmp"), ImageFormat.Bmp); } object[] r2 = ImageOps.Compress(owDir, 60, 300, true, null); CheckInt("覆盖模式处理 1 张", (int)r2[0], 1); Check("覆盖模式不留「压缩后」文件夹", Directory.Exists(Path.Combine(owDir, "压缩后")) ? "yes" : "no", "no"); Check("覆盖模式没有报错(源文件锁问题已解决)", ((string)r2[2]).Contains("失败") ? "error" : "clean", "clean"); using (Image im = Image.FromFile(Path.Combine(owDir, "notes.bmp"))) { Check("覆盖后内容仍是真 BMP(不是塞了 PNG 的假 bmp)", im.RawFormat.Guid == ImageFormat.Bmp.Guid ? "Bmp" : "other", "Bmp"); Check("覆盖后按 300 宽缩了", SizeText(im.Size), "300x200"); } } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { if (Directory.Exists(caseDir)) Directory.Delete(caseDir, true); } catch { } try { if (Directory.Exists(owDir)) Directory.Delete(owDir, 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-imgcompress.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 ImageCompressForm()); } } }