// 图片打码 - 绿色工具箱 // C# 5.0 语法,零依赖(GDI+ 系统组件) // 功能:在图片上框选区域,打马赛克 / 模糊 / 纯色块,遮住身份证号、手机号、聊天头像等隐私。 // 框选位置按比例记忆,可批量应用到整个文件夹(同尺寸截图最准)。 using System; using System.Collections.Generic; using System.ComponentModel; 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 MosaicForm : 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 RadioButton rbMosaic, rbBlur, rbSolid; private NumericUpDown numBlock, numBlur; private Button btnColor; private CheckBox chkSub, chkForceJpg; private Button btnRun, btnUndo, btnClear; private ProgressBar progress; private Label lblStatus, lblCount; private PictureBox pic; private BackgroundWorker worker; private Color curColor = Color.FromArgb(40, 40, 40); private Image previewSrc = null; private string previewPath = ""; private string[] previewFiles = new string[0]; private int previewIndex = 0; // 已框选的遮挡区域(图片真实坐标) private List regions = new List(); // 预览映射参数 private float previewScale = 1f; private int previewOx = 0, previewOy = 0; // 拖拽中的橡皮筋 private bool dragging = false; private Point dragStart = Point.Empty; private Point dragCur = Point.Empty; public MosaicForm() { 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(1000, 700); this.MinimumSize = new Size(1000, 700); this.StartPosition = FormStartPosition.CenterScreen; this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 20, y = 14; Label l0 = new Label(); l0.Text = "选文件夹 → 在右侧图上拖出要遮住的区域 → 开始打码,结果在\"打码\"子文件夹"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 26; txtFolder = new TextBox(); txtFolder.Location = new Point(x, y); txtFolder.Size = new Size(400, 26); txtFolder.ReadOnly = true; txtFolder.BackColor = COL_PANEL; this.Controls.Add(txtFolder); Button btnBrowse = Flat("浏览文件夹", new Point(428, y - 1), new Size(116, 28), false); btnBrowse.Click += new EventHandler(BrowseClick); this.Controls.Add(btnBrowse); y += 42; // ---------------- 遮挡方式 ---------------- GroupBox g1 = new GroupBox(); g1.Text = "遮挡方式"; g1.Location = new Point(x, y); g1.Size = new Size(544, 132); g1.ForeColor = COL_GREEN; g1.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g1); rbMosaic = new RadioButton(); rbMosaic.Text = "马赛克"; rbMosaic.Location = new Point(14, 26); rbMosaic.AutoSize = true; rbMosaic.Checked = true; rbMosaic.ForeColor = this.ForeColor; rbMosaic.Font = this.Font; rbMosaic.CheckedChanged += new EventHandler(AnyChange); g1.Controls.Add(rbMosaic); Label lb1 = new Label(); lb1.Text = "块大小"; lb1.AutoSize = true; lb1.ForeColor = COL_GRAY; lb1.Location = new Point(100, 28); lb1.Font = this.Font; g1.Controls.Add(lb1); numBlock = new NumericUpDown(); numBlock.Location = new Point(158, 24); numBlock.Size = new Size(62, 26); numBlock.Minimum = 2; numBlock.Maximum = 100; numBlock.Value = 12; numBlock.ValueChanged += new EventHandler(AnyChange); g1.Controls.Add(numBlock); Label lb2 = new Label(); lb2.Text = "‰(占遮挡区宽度,自动随图缩放)"; lb2.AutoSize = true; lb2.ForeColor = COL_GRAY; lb2.Location = new Point(228, 28); lb2.Font = this.Font; g1.Controls.Add(lb2); rbBlur = new RadioButton(); rbBlur.Text = "模糊"; rbBlur.Location = new Point(14, 62); rbBlur.AutoSize = true; rbBlur.ForeColor = this.ForeColor; rbBlur.Font = this.Font; rbBlur.CheckedChanged += new EventHandler(AnyChange); g1.Controls.Add(rbBlur); Label lb3 = new Label(); lb3.Text = "强度"; lb3.AutoSize = true; lb3.ForeColor = COL_GRAY; lb3.Location = new Point(100, 64); lb3.Font = this.Font; g1.Controls.Add(lb3); numBlur = new NumericUpDown(); numBlur.Location = new Point(158, 60); numBlur.Size = new Size(62, 26); numBlur.Minimum = 5; numBlur.Maximum = 100; numBlur.Value = 25; numBlur.ValueChanged += new EventHandler(AnyChange); g1.Controls.Add(numBlur); Label lb3b = new Label(); lb3b.Text = "‰(占遮挡区宽度)"; lb3b.AutoSize = true; lb3b.ForeColor = COL_GRAY; lb3b.Location = new Point(228, 64); lb3b.Font = this.Font; g1.Controls.Add(lb3b); rbSolid = new RadioButton(); rbSolid.Text = "纯色块"; rbSolid.Location = new Point(14, 96); rbSolid.AutoSize = true; rbSolid.ForeColor = this.ForeColor; rbSolid.Font = this.Font; rbSolid.CheckedChanged += new EventHandler(AnyChange); g1.Controls.Add(rbSolid); btnColor = Flat("■ 黑色", new Point(100, 90), new Size(96, 30), false); btnColor.ForeColor = Color.FromArgb(60, 66, 62); btnColor.Click += new EventHandler(PickColor); g1.Controls.Add(btnColor); Label lb4 = new Label(); lb4.Text = "报告、证件复印件常用纯色块,聊天截图常用马赛克"; lb4.AutoSize = true; lb4.ForeColor = COL_GRAY; lb4.Location = new Point(204, 96); lb4.Font = this.Font; g1.Controls.Add(lb4); y += 144; // ---------------- 框选操作 ---------------- GroupBox g2 = new GroupBox(); g2.Text = "框选区域"; g2.Location = new Point(x, y); g2.Size = new Size(544, 104); g2.ForeColor = COL_GREEN; g2.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g2); Label lh = new Label(); lh.Text = "在右边预览图上按住左键拖动,松手即添加一个遮挡块(可加多个)。"; lh.AutoSize = true; lh.ForeColor = COL_GRAY; lh.Font = this.Font; lh.Location = new Point(14, 26); g2.Controls.Add(lh); btnUndo = Flat("撤销最后一个", new Point(14, 56), new Size(120, 30), false); btnUndo.Click += new EventHandler(UndoClick); g2.Controls.Add(btnUndo); btnClear = Flat("清空全部", new Point(146, 56), new Size(100, 30), false); btnClear.Click += new EventHandler(ClearClick); g2.Controls.Add(btnClear); lblCount = new Label(); lblCount.Text = "已框选 0 处"; lblCount.AutoSize = true; lblCount.ForeColor = COL_GRAY; lblCount.Font = this.Font; lblCount.Location = new Point(262, 62); g2.Controls.Add(lblCount); y += 116; // ---------------- 输出 ---------------- GroupBox g3 = new GroupBox(); g3.Text = "输出"; g3.Location = new Point(x, y); g3.Size = new Size(544, 100); g3.ForeColor = COL_GREEN; g3.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g3); Label l5 = new Label(); l5.Text = "框的位置按比例记,会套用到这个文件夹里所有图片(同一批截图效果最好)"; l5.AutoSize = true; l5.ForeColor = COL_GRAY; l5.Font = this.Font; l5.Location = new Point(14, 26); g3.Controls.Add(l5); chkSub = new CheckBox(); chkSub.Text = "包含子文件夹"; chkSub.Location = new Point(16, 60); chkSub.AutoSize = true; chkSub.ForeColor = this.ForeColor; chkSub.Font = this.Font; g3.Controls.Add(chkSub); chkForceJpg = new CheckBox(); chkForceJpg.Text = "统一输出为 JPG"; chkForceJpg.Location = new Point(160, 60); chkForceJpg.AutoSize = true; chkForceJpg.ForeColor = this.ForeColor; chkForceJpg.Font = this.Font; g3.Controls.Add(chkForceJpg); y += 112; btnRun = new Button(); btnRun.Text = "开始打码"; btnRun.Location = new Point(x, y); btnRun.Size = new Size(150, 38); btnRun.BackColor = COL_GREEN; btnRun.ForeColor = Color.White; btnRun.FlatStyle = FlatStyle.Flat; btnRun.FlatAppearance.BorderSize = 0; btnRun.Font = new Font("Microsoft YaHei UI", 10f, FontStyle.Bold); btnRun.Click += new EventHandler(RunClick); this.Controls.Add(btnRun); progress = new ProgressBar(); progress.Location = new Point(x, y + 50); progress.Size = new Size(544, 8); this.Controls.Add(progress); lblStatus = new Label(); lblStatus.Text = "不联网、不上传,全部在本机完成。"; lblStatus.Location = new Point(x, y + 64); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); // ---------------- 预览 ---------------- GroupBox g4 = new GroupBox(); g4.Text = "预览(可直接框选)"; g4.Location = new Point(588, 14); g4.Size = new Size(396, 672); g4.ForeColor = COL_GREEN; g4.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g4); pic = new PictureBox(); pic.Location = new Point(10, 24); pic.Size = new Size(376, 596); pic.BackColor = COL_PANEL; pic.SizeMode = PictureBoxSizeMode.Normal; pic.BorderStyle = BorderStyle.FixedSingle; pic.Cursor = Cursors.Cross; pic.MouseDown += new MouseEventHandler(PicDown); pic.MouseMove += new MouseEventHandler(PicMove); pic.MouseUp += new MouseEventHandler(PicUp); g4.Controls.Add(pic); Button btnPrev = Flat("◀ 上一张", new Point(10, 630), new Size(110, 30), false); btnPrev.Click += new EventHandler(PrevClick); g4.Controls.Add(btnPrev); Button btnNext = Flat("下一张 ▶", new Point(130, 630), new Size(110, 30), false); btnNext.Click += new EventHandler(NextClick); g4.Controls.Add(btnNext); lblCount.Text = "已框选 0 处"; } private Button Flat(string text, Point loc, Size sz, bool primary) { Button b = new Button(); b.Text = text; b.Location = loc; b.Size = sz; b.FlatStyle = FlatStyle.Flat; b.FlatAppearance.BorderColor = primary ? COL_GREEN : Color.FromArgb(200, 210, 204); b.ForeColor = primary ? Color.White : Color.FromArgb(50, 58, 54); if (primary) b.BackColor = COL_GREEN; return b; } // ---------------------------------------------------------------- 交互 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) return; if (Directory.Exists(f[0])) txtFolder.Text = f[0]; else txtFolder.Text = Path.GetDirectoryName(f[0]); LoadPreview(); } private void BrowseClick(object sender, EventArgs e) { using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择要打码的图片文件夹"; if (d.ShowDialog() == DialogResult.OK) { txtFolder.Text = d.SelectedPath; LoadPreview(); } } } private void UndoClick(object sender, EventArgs e) { if (regions.Count > 0) regions.RemoveAt(regions.Count - 1); UpdateCount(); RenderPreview(); } private void ClearClick(object sender, EventArgs e) { regions.Clear(); UpdateCount(); RenderPreview(); } private void UpdateCount() { lblCount.Text = "已框选 " + regions.Count + " 处"; } private void PickColor(object sender, EventArgs e) { using (ColorDialog d = new ColorDialog()) { d.Color = curColor; d.FullOpen = true; if (d.ShowDialog() == DialogResult.OK) { curColor = d.Color; btnColor.Text = "■ " + NameOf(curColor); btnColor.ForeColor = curColor.GetBrightness() > 0.7 ? Color.FromArgb(60, 66, 62) : curColor; RenderPreview(); } } } private static string NameOf(Color c) { if (c.R > 240 && c.G > 240 && c.B > 240) return "白色"; if (c.R < 20 && c.G < 20 && c.B < 20) return "黑色"; if (c.R > 180 && c.G < 80 && c.B < 80) return "红色"; return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"); } private void AnyChange(object sender, EventArgs e) { RenderPreview(); } private void PicDown(object sender, MouseEventArgs e) { if (previewSrc == null || e.Button != MouseButtons.Left) return; dragging = true; dragStart = ToImg(e.Location); dragCur = dragStart; } private void PicMove(object sender, MouseEventArgs e) { if (!dragging) return; dragCur = ToImg(e.Location); RenderPreview(); } private void PicUp(object sender, MouseEventArgs e) { if (!dragging) return; dragging = false; Point a = dragStart, b = ToImg(e.Location); Rectangle r = RectOf(a, b); if (r.Width >= 6 && r.Height >= 6) { regions.Add(r); UpdateCount(); } RenderPreview(); } private static Rectangle RectOf(Point a, Point b) { int x = Math.Min(a.X, b.X), y = Math.Min(a.Y, b.Y); return new Rectangle(x, y, Math.Abs(a.X - b.X), Math.Abs(a.Y - b.Y)); } private Point ToImg(Point p) { if (previewSrc == null || previewScale <= 0f) return Point.Empty; int x = (int)((p.X - previewOx) / previewScale); int y = (int)((p.Y - previewOy) / previewScale); x = Math.Max(0, Math.Min(previewSrc.Width - 1, x)); y = Math.Max(0, Math.Min(previewSrc.Height - 1, y)); return new Point(x, y); } private Rectangle ToDisp(Rectangle r) { int x = (int)(r.X * previewScale) + previewOx; int y = (int)(r.Y * previewScale) + previewOy; int w = (int)Math.Round(r.Width * previewScale); int h = (int)Math.Round(r.Height * previewScale); if (w < 1) w = 1; if (h < 1) h = 1; return new Rectangle(x, y, w, h); } // ---------------------------------------------------------------- 预览 private void PrevClick(object sender, EventArgs e) { if (previewIndex > 0) { previewIndex--; ShowPreviewAt(previewIndex); } } private void NextClick(object sender, EventArgs e) { if (previewIndex < previewFiles.Length - 1) { previewIndex++; ShowPreviewAt(previewIndex); } } private void LoadPreview() { string folder = txtFolder.Text; if (folder.Length == 0 || !Directory.Exists(folder)) return; List files = Collect(folder, false); previewFiles = files.ToArray(); previewIndex = 0; if (previewFiles.Length == 0) { lblStatus.Text = "这个文件夹里没有 jpg/png/bmp 图片。"; if (previewSrc != null) { previewSrc.Dispose(); previewSrc = null; } pic.Image = null; return; } ShowPreviewAt(0); } private void ShowPreviewAt(int idx) { if (idx < 0 || idx >= previewFiles.Length) return; try { if (previewSrc != null) previewSrc.Dispose(); previewSrc = LoadPic(previewFiles[idx]); previewPath = previewFiles[idx]; lblStatus.Text = "共 " + previewFiles.Length + " 张,当前第 " + (idx + 1) + " 张:" + Path.GetFileName(previewPath) + "(" + previewSrc.Width + "×" + previewSrc.Height + ")"; RenderPreview(); } catch (Exception ex) { lblStatus.Text = "预览失败:" + ex.Message; } } private void RenderPreview() { if (previewSrc == null) return; int pw = pic.Width, ph = pic.Height; if (pw < 20 || ph < 20) return; float s = Math.Min((float)pw / previewSrc.Width, (float)ph / previewSrc.Height); if (s <= 0f) return; int dw = (int)(previewSrc.Width * s), dh = (int)(previewSrc.Height * s); int dx = (pw - dw) / 2, dy = (ph - dh) / 2; previewScale = s; previewOx = dx; previewOy = dy; Bitmap bmp = new Bitmap(pw, ph); using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(COL_PANEL); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(previewSrc, dx, dy, dw, dh); } // 在预览图上直接做效果,所见即所得 foreach (Rectangle r in regions) { Rectangle d = ToDisp(r); d.Intersect(new Rectangle(dx, dy, dw, dh)); if (d.Width < 2 || d.Height < 2) continue; ApplyEffect(bmp, d, false); } // 边框 using (Graphics g = Graphics.FromImage(bmp)) { foreach (Rectangle r in regions) { Rectangle d = ToDisp(r); using (Pen pw1 = new Pen(Color.White, 3f)) using (Pen pg = new Pen(COL_GREEN, 1f)) { pw1.Alignment = PenAlignment.Inset; pg.Alignment = PenAlignment.Inset; g.DrawRectangle(pw1, d); g.DrawRectangle(pg, d); } } if (dragging) { Rectangle d = ToDisp(RectOf(dragStart, dragCur)); using (Pen pen = new Pen(Color.FromArgb(230, 30, 60, 220), 1.5f)) { pen.DashStyle = DashStyle.Dash; g.DrawRectangle(pen, d); } } } Image old = pic.Image; pic.Image = bmp; if (old != null && old != previewSrc) old.Dispose(); } // ---------------------------------------------------------------- 效果 private void ApplyEffect(Bitmap bmp, Rectangle r, bool fullQuality) { r.Intersect(new Rectangle(0, 0, bmp.Width, bmp.Height)); if (r.Width < 2 || r.Height < 2) return; if (rbSolid.Checked) { using (Graphics g = Graphics.FromImage(bmp)) { g.CompositingMode = CompositingMode.SourceCopy; using (SolidBrush br = new SolidBrush(curColor)) g.FillRectangle(br, r); } return; } if (rbMosaic.Checked) { // 块大小按遮挡区宽度的千分比算,大图小图都能遮干净 int block = Math.Max(2, r.Width * (int)numBlock.Value / 1000); Pixelate(bmp, r, block); return; } // 模糊:缩到很小再放大,等效大半径模糊,速度极快;强度按遮挡区宽度千分比 int k = Math.Max(2, r.Width * (int)numBlur.Value / 1000); int sw = Math.Max(1, r.Width / k), sh = Math.Max(1, r.Height / k); using (Bitmap small = new Bitmap(sw, sh, PixelFormat.Format24bppRgb)) { using (Graphics gs = Graphics.FromImage(small)) { gs.InterpolationMode = InterpolationMode.HighQualityBilinear; gs.PixelOffsetMode = PixelOffsetMode.HighQuality; gs.DrawImage(bmp, new Rectangle(0, 0, sw, sh), r, GraphicsUnit.Pixel); } using (Graphics g = Graphics.FromImage(bmp)) { g.CompositingMode = CompositingMode.SourceCopy; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(small, r); } } } private static void Pixelate(Bitmap bmp, Rectangle r, int block) { if (block < 2) block = 2; int bw = r.Width, bh = r.Height; using (Bitmap tmp = new Bitmap(bw, bh, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(tmp)) { g.CompositingMode = CompositingMode.SourceCopy; g.DrawImage(bmp, new Rectangle(0, 0, bw, bh), r, GraphicsUnit.Pixel); } BitmapData bd = tmp.LockBits(new Rectangle(0, 0, bw, bh), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); try { int stride = Math.Abs(bd.Stride); byte[] buf = new byte[stride * bh]; Marshal.Copy(bd.Scan0, buf, 0, buf.Length); for (int by = 0; by < bh; by += block) { int hh = Math.Min(block, bh - by); for (int bx = 0; bx < bw; bx += block) { int ww = Math.Min(block, bw - bx); long sr = 0, sg = 0, sb = 0; int n = 0; for (int yy = 0; yy < hh; yy++) { int off = (by + yy) * stride + bx * 3; for (int xx = 0; xx < ww; xx++) { sb += buf[off]; sg += buf[off + 1]; sr += buf[off + 2]; off += 3; n++; } } if (n == 0) continue; byte bb = (byte)(sb / n), bg = (byte)(sg / n), br = (byte)(sr / n); for (int yy = 0; yy < hh; yy++) { int off = (by + yy) * stride + bx * 3; for (int xx = 0; xx < ww; xx++) { buf[off] = bb; buf[off + 1] = bg; buf[off + 2] = br; off += 3; } } } } Marshal.Copy(buf, 0, bd.Scan0, buf.Length); } finally { tmp.UnlockBits(bd); } using (Graphics g = Graphics.FromImage(bmp)) { g.CompositingMode = CompositingMode.SourceCopy; g.DrawImage(tmp, r); } } } // ---------------------------------------------------------------- 批量 private static List Collect(string folder, bool sub) { string[] exts = new string[] { "*.jpg", "*.jpeg", "*.png", "*.bmp" }; List list = new List(); SearchOption opt = sub ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; foreach (string pat in exts) foreach (string f in Directory.GetFiles(folder, pat, opt)) if (Path.GetFileName(f).StartsWith("~")) continue; else list.Add(f); list.Sort(StringComparer.OrdinalIgnoreCase); return list; } private static Image LoadPic(string path) { Image src = Image.FromFile(path); try { if (Array.IndexOf(src.PropertyIdList, 274) > -1) { int o = src.GetPropertyItem(274).Value[0]; RotateFlipType rft = RotateFlipType.RotateNoneFlipNone; if (o == 3) rft = RotateFlipType.Rotate180FlipNone; else if (o == 6) rft = RotateFlipType.Rotate90FlipNone; else if (o == 8) rft = RotateFlipType.Rotate270FlipNone; if (rft != RotateFlipType.RotateNoneFlipNone) { src.RotateFlip(rft); try { src.RemovePropertyItem(274); } catch { } } } } catch { } return src; } private void RunClick(object sender, EventArgs e) { if (txtFolder.Text.Length == 0 || !Directory.Exists(txtFolder.Text)) { lblStatus.Text = "请先选择文件夹。"; return; } if (regions.Count == 0 || previewSrc == null) { lblStatus.Text = "还没框选区域:请在右侧预览图上按住鼠标拖出要遮住的地方。"; return; } if (worker.IsBusy) return; btnRun.Enabled = false; progress.Value = 0; lblStatus.Text = "开始处理…"; worker.RunWorkerAsync(txtFolder.Text); } private void Work(object sender, DoWorkEventArgs e) { string folder = (string)e.Argument; List files = Collect(folder, chkSub.Checked); string outDir = Path.Combine(folder, "打码"); Directory.CreateDirectory(outDir); // 记录比例,套用到每张图 List rel = new List(); foreach (Rectangle r in regions) { rel.Add(new double[] { (double)r.X / previewSrc.Width, (double)r.Y / previewSrc.Height, (double)r.Width / previewSrc.Width, (double)r.Height / previewSrc.Height }); } ImageCodecInfo jpeg = GetJpegCodec(); int ok = 0, fail = 0, idx = 0; StringBuilder log = new StringBuilder(); foreach (string f in files) { idx++; try { string ext = chkForceJpg.Checked ? ".jpg" : KeepExt(f); string outPath = Path.Combine(outDir, Path.GetFileNameWithoutExtension(f) + ext); using (Image img = LoadPic(f)) using (Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(bmp)) { g.DrawImage(img, 0, 0, img.Width, img.Height); } foreach (double[] p in rel) { int rx = (int)Math.Round(p[0] * bmp.Width); int ry = (int)Math.Round(p[1] * bmp.Height); int rw = (int)Math.Round(p[2] * bmp.Width); int rh = (int)Math.Round(p[3] * bmp.Height); if (rw < 2 || rh < 2) continue; ApplyEffect(bmp, new Rectangle(rx, ry, rw, rh), true); } SaveAs(bmp, outPath, jpeg, 92); } ok++; log.AppendLine("OK " + Path.GetFileName(f) + " -> " + Path.GetFileName(outPath)); } catch (Exception ex) { fail++; log.AppendLine("失败 " + Path.GetFileName(f) + ": " + ex.Message); } ((BackgroundWorker)sender).ReportProgress(idx * 100 / Math.Max(files.Count, 1), log.ToString()); } e.Result = new object[] { files.Count, ok, fail, outDir, log.ToString() }; } private static void SaveAs(Bitmap bmp, string path, ImageCodecInfo jpeg, long quality) { if (path.ToLower().EndsWith(".png")) bmp.Save(path, ImageFormat.Png); else if (path.ToLower().EndsWith(".bmp")) bmp.Save(path, ImageFormat.Bmp); else if (jpeg != null) bmp.Save(path, jpeg, Q(quality)); else bmp.Save(path, ImageFormat.Jpeg); } private static string KeepExt(string f) { string e = Path.GetExtension(f).ToLower(); if (e == ".png") return ".png"; if (e == ".bmp") return ".bmp"; return ".jpg"; } private static EncoderParameters Q(long quality) { EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); return ep; } private static ImageCodecInfo GetJpegCodec() { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo c in codecs) if (c.FormatID == ImageFormat.Jpeg.Guid) return c; return null; } private void Prog(object sender, ProgressChangedEventArgs e) { progress.Value = e.ProgressPercentage; if (e.UserState != null) { string s = (string)e.UserState; string[] parts = s.Split('\n'); for (int i = parts.Length - 1; i >= 0; i--) { string t = parts[i].Trim(); if (t.Length > 0) { lblStatus.Text = t; break; } } } } private void Done(object sender, RunWorkerCompletedEventArgs e) { btnRun.Enabled = true; progress.Value = 100; if (e.Error != null) { lblStatus.Text = "出错了:" + e.Error.Message; return; } object[] r = (object[])e.Result; lblStatus.Text = "完成:处理 " + r[1] + " 张" + (Convert.ToInt32(r[2]) > 0 ? ",失败 " + r[2] + " 张" : "") + "。结果在 " + r[3]; } protected override void OnFormClosed(FormClosedEventArgs e) { if (previewSrc != null) previewSrc.Dispose(); base.OnFormClosed(e); } // 自测入口 public object[] RunBatch(string folder) { BackgroundWorker w = new BackgroundWorker(); w.WorkerReportsProgress = true; DoWorkEventArgs ev = new DoWorkEventArgs(folder); Work(w, ev); return (object[])ev.Result; } // 自测用:打开文件夹并框选中间一半区域 public void LoadFolderForTest(string folder) { txtFolder.Text = folder; LoadPreview(); } // 自测用:把中间一半区域设为遮挡块 public void SetForTest(string kind) { if (previewSrc == null) return; regions.Clear(); int w = previewSrc.Width, h = previewSrc.Height; regions.Add(new Rectangle(w / 4, h / 4, w / 2, h / 2)); if (kind == "blur") { rbBlur.Checked = true; } else if (kind == "solid") { rbSolid.Checked = true; } else { rbMosaic.Checked = true; } } } // 命令行自测:细格纹图 → 三种打码各跑一遍 → 断言「框里花掉、框外没动」 public static class SelfTest { private static int _pass = 0; private static int _fail = 0; private static List _lines = new List(); private static void Check(string name, string got, string want) { if (got == want) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " 期望[" + want + "] 实际[" + got + "]"); } } private static void CheckInt(string name, int got, int want) { Check(name, got.ToString(), want.ToString()); } private static void CheckLess(string name, int got, int ceil) { if (got < ceil) { _pass++; _lines.Add(" [ok] " + name + "(" + got + ")"); } else { _fail++; _lines.Add(" [!!] " + name + " 期望<" + ceil + " 实际[" + got + "]"); } } private static Image Load(string path) { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (MemoryStream ms = new MemoryStream()) { fs.CopyTo(ms); ms.Position = 0; return Image.FromStream(ms); } } // 一块区域里有几种颜色:打码成功=颜色数暴跌(纯色遮挡=只剩 1 种) private static int ColorsIn(Image img, int x0, int y0, int x1, int y1) { using (Bitmap b = new Bitmap(img)) { Dictionary seen = new Dictionary(); if (x1 > b.Width) x1 = b.Width; if (y1 > b.Height) y1 = b.Height; for (int y = y0; y < y1; y++) for (int x = x0; x < x1; x++) { int argb = b.GetPixel(x, y).ToArgb(); if (!seen.ContainsKey(argb)) seen[argb] = 1; } return seen.Count; } } // 相邻像素差异大于阈值的对数 = 这块区域的「细节量」。 // 打码/模糊/纯色遮挡都会让它掉下来,比「数颜色种数」稳(合成图本来只有两种颜色) private static int EdgeCount(Image img, int x0, int y0, int x1, int y1) { using (Bitmap b = new Bitmap(img)) { int n = 0; if (x1 > b.Width) x1 = b.Width; if (y1 > b.Height) y1 = b.Height; for (int y = y0; y < y1; y++) for (int x = x0; x < x1 - 1; x++) { Color a = b.GetPixel(x, y), c = b.GetPixel(x + 1, y); if (Math.Abs(a.R - c.R) > 32 || Math.Abs(a.G - c.G) > 32 || Math.Abs(a.B - c.B) > 32) n++; } return n; } } private static Color Pixel(Image img, int x, int y) { using (Bitmap b = new Bitmap(img)) return b.GetPixel(x, y); } // 4px 细格纹:不打码时颜色极多,打码后立刻糊成一片 private static string NewCase(string root, string name) { string d = Path.Combine(root, name); Directory.CreateDirectory(d); // 确定性噪点:逐像素乱跳,打码/模糊之后一定会变平滑,最适合量「细节掉没掉」 using (Bitmap b = new Bitmap(400, 300)) { for (int y = 0; y < 300; y++) for (int x = 0; x < 400; x++) { int v = (x * 7919 + y * 104729 + x * y * 31) % 256; b.SetPixel(x, y, Color.FromArgb(v, (v * 5) % 256, (v * 11) % 256)); } b.Save(Path.Combine(d, "doc.png"), ImageFormat.Png); } return d; } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-mosaic-selftest"); try { if (Directory.Exists(dir)) { try { Directory.Delete(dir, true); } catch { } } Directory.CreateDirectory(dir); _lines.Add("图片打码 自测(" + dir + ")"); string cM = NewCase(dir, "mosaic"); string cB = NewCase(dir, "blur"); string cS = NewCase(dir, "solid"); string cE = Path.Combine(dir, "empty"); Directory.CreateDirectory(cE); int srcEdges; Color srcTL; using (Image src = Load(Path.Combine(cM, "doc.png"))) { srcEdges = EdgeCount(src, 100, 75, 300, 225); srcTL = Pixel(src, 2, 2); } Check("自测用的源图够花(细节基准够大)", srcEdges > 500 ? "够" : "不够", "够"); // ① 马赛克 MosaicForm f = new MosaicForm(); f.LoadFolderForTest(cM); f.SetForTest("mosaic"); object[] r1 = f.RunBatch(cM); CheckInt("马赛克:处理 1 张", (int)r1[1], 1); CheckInt("马赛克:失败 0 张", (int)r1[2], 0); string o1 = Path.Combine(cM, "打码", "doc.png"); Check("马赛克:产出 doc.png(png 进 png 出)", File.Exists(o1) ? "在" : "不在", "在"); using (Image im1 = Load(o1)) { Check("马赛克:尺寸没变", im1.Width + "x" + im1.Height, "400x300"); // 中间那块被糊掉:颜色数应该从上千掉到很少 CheckLess("马赛克:框内细节明显变少(块内被平均掉)", EdgeCount(im1, 100, 75, 300, 225), srcEdges * 6 / 10); Check("马赛克:框外左上角没动", Near(Pixel(im1, 2, 2), srcTL), "是"); } // ② 模糊 f.LoadFolderForTest(cB); f.SetForTest("blur"); object[] r2 = f.RunBatch(cB); CheckInt("模糊:处理 1 张", (int)r2[1], 1); using (Image im2 = Load(Path.Combine(cB, "打码", "doc.png"))) CheckLess("模糊:框内细节基本被抹平", EdgeCount(im2, 100, 75, 300, 225), srcEdges / 4); // ③ 纯色遮挡:框内应当只剩一种颜色 f.LoadFolderForTest(cS); f.SetForTest("solid"); object[] r3 = f.RunBatch(cS); CheckInt("纯色:处理 1 张", (int)r3[1], 1); using (Image im3 = Load(Path.Combine(cS, "打码", "doc.png"))) { CheckInt("纯色:框内只剩一种颜色", ColorsIn(im3, 110, 85, 290, 215), 1); CheckInt("纯色:框内一点细节都不剩", EdgeCount(im3, 100, 75, 300, 225), 0); } // ④ 空文件夹不炸 object[] r4 = f.RunBatch(cE); CheckInt("空文件夹:处理 0 张", (int)r4[1], 0); CheckInt("空文件夹:不报失败", (int)r4[2], 0); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } _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-mosaic.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } private static string Near(Color got, Color want) { bool ok = Math.Abs(got.R - want.R) <= 8 && Math.Abs(got.G - want.G) <= 8 && Math.Abs(got.B - want.B) <= 8; return ok ? "是" : "否(" + got.R + "," + got.G + "," + got.B + ")"; } } static class Program { [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // 自测:MosaicTool.exe --selftest [工作目录] (退出码 0 全过 / 1 有失败) if (args.Length >= 1 && args[0] == "--selftest") { Environment.Exit(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } // 临时驱动(截图/核对脚本用):--batch <图片文件夹> [mosaic|blur|solid] if (args.Length >= 2 && args[0] == "--batch") { MosaicForm f = new MosaicForm(); string kind = args.Length >= 3 ? args[2] : "mosaic"; f.LoadFolderForTest(args[1]); f.SetForTest(kind); object[] r = f.RunBatch(args[1]); Console.WriteLine("files=" + r[0] + " ok=" + r[1] + " fail=" + r[2] + " out=" + r[3]); return; } Application.Run(new MosaicForm()); } } }