// 证件照换底色 - 绿色工具箱 // C# 5.0 语法,零依赖(GDI+ 系统组件) // 功能:把证件照的纯色/近纯色背景换成白、蓝、红,并裁成一寸/二寸等标准尺寸,输出 300dpi 的 JPG。 // 做法是从四角(以及用户点选的位置)出发做容差填充,不联网、不调用任何模型,全程本机。 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 IdPhotoForm : 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 static readonly string[] SIZE_NAMES = new string[] { "一寸 25×35mm(295×413)", "小一寸 22×32mm(260×378)", "大一寸 33×48mm(390×567)", "二寸 35×49mm(413×579)", "小二寸 35×45mm(413×531)", "护照 33×48mm(390×567)", "美国签证 2×2in(600×600)", "身份证 26×32mm(358×441)" }; private static readonly int[][] SIZE_PX = new int[][] { new int[] { 295, 413 }, new int[] { 260, 378 }, new int[] { 390, 567 }, new int[] { 413, 579 }, new int[] { 413, 531 }, new int[] { 390, 567 }, new int[] { 600, 600 }, new int[] { 358, 441 } }; private TextBox txtFile; private ComboBox cmbSize; private ComboBox cmbBg; private Button btnCustomColor; private NumericUpDown numTol, numFeather, numOffset; private CheckBox chkSeedCorners; private Button btnSave, btnReset; private Label lblStatus; private PictureBox pic; private Color bgColor = Color.White; private Image src = null; private string srcPath = ""; private Bitmap pv = null; // 预览用的缩放副本 private float pvScale = 1f; // 预览副本相对原图的比例 private List seeds = new List(); // 原图坐标的取样点 private bool headless = false; // 自测时不弹窗,直接抛错 private float previewScale = 1f; private int previewOx = 0, previewOy = 0; public IdPhotoForm() { InitUi(); } 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(940, 700); this.MinimumSize = new Size(940, 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; txtFile = new TextBox(); txtFile.Location = new Point(x, y); txtFile.Size = new Size(400, 26); txtFile.ReadOnly = true; txtFile.BackColor = COL_PANEL; this.Controls.Add(txtFile); Button btnBrowse = Flat("选择照片…", new Point(428, y - 1), new Size(110, 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(504, 94); g1.ForeColor = COL_GREEN; g1.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g1); cmbBg = new ComboBox(); cmbBg.DropDownStyle = ComboBoxStyle.DropDownList; cmbBg.Location = new Point(14, 30); cmbBg.Size = new Size(190, 26); cmbBg.Items.AddRange(new object[] { "白色(常用)", "蓝色(证件/简历)", "红色(结婚/荣誉)", "浅灰", "自定义颜色" }); cmbBg.SelectedIndex = 0; cmbBg.SelectedIndexChanged += new EventHandler(BgChange); g1.Controls.Add(cmbBg); btnCustomColor = Flat("■ 白", new Point(216, 28), new Size(70, 28), false); btnCustomColor.Enabled = false; btnCustomColor.Click += new EventHandler(PickColor); g1.Controls.Add(btnCustomColor); Label l1 = new Label(); l1.Text = "容差"; l1.AutoSize = true; l1.ForeColor = COL_GRAY; l1.Location = new Point(14, 62); l1.Font = this.Font; g1.Controls.Add(l1); numTol = new NumericUpDown(); numTol.Location = new Point(56, 58); numTol.Size = new Size(60, 26); numTol.Minimum = 5; numTol.Maximum = 120; numTol.Value = 40; numTol.ValueChanged += new EventHandler(AnyChange); g1.Controls.Add(numTol); Label l2 = new Label(); l2.Text = "背景越花就要调大,调太大人脸也会被换掉"; l2.AutoSize = true; l2.ForeColor = COL_GRAY; l2.Location = new Point(124, 62); l2.Font = this.Font; g1.Controls.Add(l2); y += 106; // ---------------- 尺寸 ---------------- GroupBox g2 = new GroupBox(); g2.Text = "尺寸与裁切"; g2.Location = new Point(x, y); g2.Size = new Size(504, 132); g2.ForeColor = COL_GREEN; g2.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g2); Label l3 = new Label(); l3.Text = "规格"; l3.AutoSize = true; l3.ForeColor = COL_GRAY; l3.Location = new Point(14, 30); l3.Font = this.Font; g2.Controls.Add(l3); cmbSize = new ComboBox(); cmbSize.DropDownStyle = ComboBoxStyle.DropDownList; cmbSize.Location = new Point(56, 26); cmbSize.Size = new Size(266, 26); cmbSize.Items.AddRange(SIZE_NAMES); cmbSize.SelectedIndex = 0; cmbSize.SelectedIndexChanged += new EventHandler(AnyChange); g2.Controls.Add(cmbSize); Label l4 = new Label(); l4.Text = "上下位置"; l4.AutoSize = true; l4.ForeColor = COL_GRAY; l4.Location = new Point(14, 70); l4.Font = this.Font; g2.Controls.Add(l4); numOffset = new NumericUpDown(); numOffset.Location = new Point(82, 66); numOffset.Size = new Size(60, 26); numOffset.Minimum = -100; numOffset.Maximum = 100; numOffset.Value = 0; numOffset.ValueChanged += new EventHandler(AnyChange); g2.Controls.Add(numOffset); Label l5 = new Label(); l5.Text = "负数往上裁(头离顶更近),正数往下"; l5.AutoSize = true; l5.ForeColor = COL_GRAY; l5.Location = new Point(150, 70); l5.Font = this.Font; g2.Controls.Add(l5); Label l6 = new Label(); l6.Text = "边缘柔化"; l6.AutoSize = true; l6.ForeColor = COL_GRAY; l6.Location = new Point(14, 102); l6.Font = this.Font; g2.Controls.Add(l6); numFeather = new NumericUpDown(); numFeather.Location = new Point(82, 98); numFeather.Size = new Size(60, 26); numFeather.Minimum = 0; numFeather.Maximum = 6; numFeather.Value = 1; numFeather.ValueChanged += new EventHandler(AnyChange); g2.Controls.Add(numFeather); Label l7 = new Label(); l7.Text = "像素(发丝附近有毛边就调大)"; l7.AutoSize = true; l7.ForeColor = COL_GRAY; l7.Location = new Point(150, 102); l7.Font = this.Font; g2.Controls.Add(l7); y += 144; // ---------------- 取样 ---------------- GroupBox g3 = new GroupBox(); g3.Text = "背景取样"; g3.Location = new Point(x, y); g3.Size = new Size(504, 92); g3.ForeColor = COL_GREEN; g3.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g3); chkSeedCorners = new CheckBox(); chkSeedCorners.Text = "自动取四角做种子"; chkSeedCorners.Location = new Point(14, 28); chkSeedCorners.AutoSize = true; chkSeedCorners.Checked = true; chkSeedCorners.ForeColor = this.ForeColor; chkSeedCorners.Font = this.Font; chkSeedCorners.CheckedChanged += new EventHandler(AnyChange); g3.Controls.Add(chkSeedCorners); Label l8 = new Label(); l8.Text = "背景不是纯色(渐变、窗帘、墙角)就在右边多点几处背景"; l8.AutoSize = true; l8.ForeColor = COL_GRAY; l8.Font = this.Font; l8.Location = new Point(14, 60); g3.Controls.Add(l8); y += 104; btnSave = new Button(); btnSave.Text = "保存证件照…"; btnSave.Location = new Point(x, y); btnSave.Size = new Size(150, 38); btnSave.BackColor = COL_GREEN; btnSave.ForeColor = Color.White; btnSave.FlatStyle = FlatStyle.Flat; btnSave.FlatAppearance.BorderSize = 0; btnSave.Font = new Font("Microsoft YaHei UI", 10f, FontStyle.Bold); btnSave.Click += new EventHandler(SaveClick); this.Controls.Add(btnSave); btnReset = Flat("重置取样点", new Point(162, y + 3), new Size(104, 32), false); btnReset.Click += new EventHandler(ResetClick); this.Controls.Add(btnReset); lblStatus = new Label(); lblStatus.Text = "不联网、不上传,照片不出本机。"; lblStatus.Location = new Point(x, y + 48); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); // ---------------- 预览 ---------------- GroupBox g4 = new GroupBox(); g4.Text = "预览(点一下背景可加取样点)"; g4.Location = new Point(540, 14); g4.Size = new Size(384, 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(362, 632); pic.BackColor = COL_PANEL; pic.SizeMode = PictureBoxSizeMode.Normal; pic.BorderStyle = BorderStyle.FixedSingle; pic.Cursor = Cursors.Hand; pic.MouseDown += new MouseEventHandler(PicDown); g4.Controls.Add(pic); } 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; LoadFile(f[0]); } private void BrowseClick(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "图片|*.jpg;*.jpeg;*.png;*.bmp"; d.Title = "选择证件照(背景尽量是纯色)"; if (d.ShowDialog() == DialogResult.OK) LoadFile(d.FileName); } } private void BgChange(object sender, EventArgs e) { int i = cmbBg.SelectedIndex; btnCustomColor.Enabled = (i == 4); if (i == 0) bgColor = Color.White; else if (i == 1) bgColor = Color.FromArgb(67, 142, 219); else if (i == 2) bgColor = Color.FromArgb(215, 0, 15); else if (i == 3) bgColor = Color.FromArgb(238, 238, 238); btnCustomColor.Text = "■ " + NameOf(bgColor); Render(); } private void PickColor(object sender, EventArgs e) { using (ColorDialog d = new ColorDialog()) { d.Color = bgColor; d.FullOpen = true; if (d.ShowDialog() == DialogResult.OK) { bgColor = d.Color; btnCustomColor.Text = "■ " + NameOf(bgColor); Render(); } } } 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.B > c.R + 40) return "蓝色"; if (c.R > c.G + 40) return "红色"; return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"); } private void AnyChange(object sender, EventArgs e) { Render(); } private void ResetClick(object sender, EventArgs e) { seeds.Clear(); Render(); } private void PicDown(object sender, MouseEventArgs e) { if (src == null || e.Button != MouseButtons.Left) return; Point p = ToImg(e.Location); if (p.X < 0) return; seeds.Add(p); Render(); } private Point ToImg(Point p) { if (src == null || previewScale <= 0f) return new Point(-1, -1); int ix = (int)((p.X - previewOx) / previewScale); int iy = (int)((p.Y - previewOy) / previewScale); if (ix < 0 || iy < 0 || ix >= src.Width || iy >= src.Height) return new Point(-1, -1); return new Point(ix, iy); } // ---------------------------------------------------------------- 载入 private void LoadFile(string path) { try { if (src != null) src.Dispose(); if (pv != null) { pv.Dispose(); pv = null; } src = LoadPic(path); srcPath = path; seeds.Clear(); txtFile.Text = path; lblStatus.Text = "已载入 " + Path.GetFileName(path) + "(" + src.Width + "×" + src.Height + ")"; BuildPreviewCopy(); Render(); } catch (Exception ex) { if (headless) throw new Exception("打不开 " + path + ":" + ex.Message); MessageBox.Show("这张图片打不开:" + ex.Message, "打不开", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void BuildPreviewCopy() { if (src == null) return; // 预览副本最长边 560px,够看清又不卡 int maxSide = 560; int w = src.Width, h = src.Height; pvScale = Math.Min(1f, Math.Min((float)maxSide / w, (float)maxSide / h)); int pw = Math.Max(1, (int)(w * pvScale)), ph = Math.Max(1, (int)(h * pvScale)); if (pv != null) pv.Dispose(); pv = new Bitmap(pw, ph, PixelFormat.Format24bppRgb); using (Graphics g = Graphics.FromImage(pv)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(src, 0, 0, pw, ph); } } private static Image LoadPic(string path) { Image img = Image.FromFile(path); try { if (Array.IndexOf(img.PropertyIdList, 274) > -1) { int o = img.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) { img.RotateFlip(rft); try { img.RemovePropertyItem(274); } catch { } } } } catch { } return img; } // ---------------------------------------------------------------- 预览 private void Render() { if (src == null || pv == null) return; int pw = pic.Width, ph = pic.Height; if (pw < 20 || ph < 20) return; float s = Math.Min((float)pw / pv.Width, (float)ph / pv.Height); int dw = (int)(pv.Width * s), dh = (int)(pv.Height * s); int dx = (pw - dw) / 2, dy = (ph - dh) / 2; Bitmap bmp = new Bitmap(pw, ph); using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(COL_PANEL); g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(pv, dx, dy, dw, dh); } // 在预览上做换底色,位置与最终结果对应 byte[] mask = BuildMask(pv.Width, pv.Height, (int)numTol.Value, true); if (mask != null) { using (Graphics g = Graphics.FromImage(bmp)) { using (Bitmap ov = ComposeOverlay(pv, mask, bgColor, (int)numFeather.Value)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(ov, dx, dy, dw, dh); } } } // 预览映射(给点击取样用) previewScale = s * (float)dw / pv.Width * pvScale; // pv.Width = src.Width * pvScale,显示宽 dw = pv.Width * s // 所以 1 原图像素 = s * pvScale 显示像素 previewScale = s * pvScale; previewOx = dx; previewOy = dy; using (Graphics g = Graphics.FromImage(bmp)) { // 裁切框 int outW, outH; GetOutSize(out outW, out outH); double cwImg, chImg, cyImg; CropGeom(outW, outH, out cwImg, out chImg, out cyImg); Rectangle cr = new Rectangle( dx + (int)((src.Width - cwImg) / 2 * previewScale), dy + (int)(cyImg * previewScale), (int)(cwImg * previewScale), (int)(chImg * previewScale)); using (Pen p1 = new Pen(Color.FromArgb(230, 255, 255, 255), 3f)) using (Pen p2 = new Pen(COL_GREEN, 1f)) { p1.Alignment = PenAlignment.Inset; p2.Alignment = PenAlignment.Inset; g.DrawRectangle(p1, cr); g.DrawRectangle(p2, cr); } // 取样点 foreach (Point sp in seeds) { float cx = dx + sp.X * previewScale, cy = dy + sp.Y * previewScale; using (Pen pen = new Pen(Color.FromArgb(230, 255, 60, 60), 1.6f)) { g.DrawLine(pen, cx - 5, cy, cx + 5, cy); g.DrawLine(pen, cx, cy - 5, cx, cy + 5); } } } Image old = pic.Image; pic.Image = bmp; if (old != null) old.Dispose(); } // ---------------------------------------------------------------- 核心算法 // 生成背景掩膜:1 = 背景,0 = 人像 private byte[] BuildMask(int w, int h, int tol, bool useSeeds) { Bitmap baseBmp = (useSeeds && w == pv.Width) ? pv : null; if (baseBmp == null) return null; int stride = w * 3; byte[] pix = new byte[stride * h]; BitmapData bd = baseBmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { for (int y = 0; y < h; y++) Marshal.Copy(new IntPtr(bd.Scan0.ToInt64() + (long)y * bd.Stride), pix, y * stride, stride); } finally { baseBmp.UnlockBits(bd); } List starts = new List(); int inset = 2; if (chkSeedCorners.Checked) { // 只用四角。不能加边中点:证件照的肩膀经常顶到左右和底边, // 种子落在人像上会把整个人像当成背景填掉。 starts.Add(new Point(inset, inset)); starts.Add(new Point(w - 1 - inset, inset)); starts.Add(new Point(inset, h - 1 - inset)); starts.Add(new Point(w - 1 - inset, h - 1 - inset)); } foreach (Point s in seeds) { int sx = (int)(s.X * pvScale), sy = (int)(s.Y * pvScale); if (sx < 0 || sy < 0 || sx >= w || sy >= h) continue; starts.Add(new Point(sx, sy)); } if (starts.Count == 0) return null; // 参考色 = 第一个种子的颜色;颜色差超过容差的种子丢弃, // 防止某个种子恰好落在人像上(衣服、头发贴边)把人像填掉 int ro0 = starts[0].Y * stride + starts[0].X * 3; byte rr = pix[ro0 + 2], rg = pix[ro0 + 1], rb = pix[ro0]; List use = new List(); foreach (Point s in starts) { int off = s.Y * stride + s.X * 3; int dr = Math.Abs(pix[off + 2] - rr); int dg = Math.Abs(pix[off + 1] - rg); int db = Math.Abs(pix[off] - rb); int d = dr > dg ? (dr > db ? dr : db) : (dg > db ? dg : db); if (d <= tol) use.Add(s); } if (use.Count == 0) return null; byte[] mask = new byte[w * h]; // 每个像素最多被入栈 4 次(来自四邻),预留足够的栈空间,避免大图上越界 int[] stack = new int[w * h * 4]; int cap = stack.Length; foreach (Point s in use) { int si = s.Y * w + s.X; if (mask[si] == 1) continue; int off0 = s.Y * stride + s.X * 3; byte r0 = pix[off0 + 2], g0 = pix[off0 + 1], b0 = pix[off0]; int sp = 0; stack[sp++] = si; while (sp > 0) { int cur = stack[--sp]; if (mask[cur] == 1) continue; int cx = cur % w, cy = cur / w; int off = cy * stride + cx * 3; int dr = Math.Abs(pix[off + 2] - r0); int dg = Math.Abs(pix[off + 1] - g0); int db = Math.Abs(pix[off] - b0); int d = dr > dg ? (dr > db ? dr : db) : (dg > db ? dg : db); if (d > tol) continue; mask[cur] = 1; if (cx > 0 && mask[cur - 1] == 0 && sp < cap) stack[sp++] = cur - 1; if (cx < w - 1 && mask[cur + 1] == 0 && sp < cap) stack[sp++] = cur + 1; if (cy > 0 && mask[cur - w] == 0 && sp < cap) stack[sp++] = cur - w; if (cy < h - 1 && mask[cur + w] == 0 && sp < cap) stack[sp++] = cur + w; } } return mask; } // 用掩膜把 base 的背景换成 bg,边缘按 feather 做柔化 private static Bitmap ComposeOverlay(Bitmap baseBmp, byte[] mask, Color bg, int feather) { int w = baseBmp.Width, h = baseBmp.Height; Bitmap outBmp = new Bitmap(w, h, PixelFormat.Format24bppRgb); using (Graphics g = Graphics.FromImage(outBmp)) { g.CompositingMode = CompositingMode.SourceCopy; g.DrawImage(baseBmp, 0, 0, w, h); } // 掩膜转 alpha 图,再按 feather 模糊,得到软边 Bitmap alphaBmp = new Bitmap(w, h, PixelFormat.Format24bppRgb); BitmapData abd = alphaBmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); int astride = abd.Stride; byte[] abuf = new byte[Math.Abs(astride) * h]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { byte v = mask[y * w + x] == 1 ? (byte)255 : (byte)0; int off = y * astride + x * 3; abuf[off] = v; abuf[off + 1] = v; abuf[off + 2] = v; } Marshal.Copy(abuf, 0, abd.Scan0, abuf.Length); alphaBmp.UnlockBits(abd); if (feather > 0) { int k = feather * 2 + 1; using (Bitmap small = new Bitmap(Math.Max(1, w / k), Math.Max(1, h / k), PixelFormat.Format24bppRgb)) { using (Graphics gs = Graphics.FromImage(small)) { gs.InterpolationMode = InterpolationMode.HighQualityBilinear; gs.DrawImage(alphaBmp, new Rectangle(0, 0, small.Width, small.Height)); } using (Graphics gb = Graphics.FromImage(alphaBmp)) { gb.CompositingMode = CompositingMode.SourceCopy; gb.InterpolationMode = InterpolationMode.HighQualityBicubic; gb.DrawImage(small, new Rectangle(0, 0, w, h)); } } } BitmapData obd = outBmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); BitmapData abd2 = alphaBmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { int ostride = obd.Stride; byte[] obuf = new byte[Math.Abs(ostride) * h]; Marshal.Copy(obd.Scan0, obuf, 0, obuf.Length); byte[] abuf2 = new byte[Math.Abs(abd2.Stride) * h]; Marshal.Copy(abd2.Scan0, abuf2, 0, abuf2.Length); for (int y = 0; y < h; y++) { int oo = y * ostride, ao = y * abd2.Stride; for (int x = 0; x < w; x++) { int a = abuf2[ao + x * 3]; if (a == 0) continue; int i = oo + x * 3; if (a == 255) { obuf[i] = bg.B; obuf[i + 1] = bg.G; obuf[i + 2] = bg.R; } else { obuf[i] = (byte)((obuf[i] * (255 - a) + bg.B * a) / 255); obuf[i + 1] = (byte)((obuf[i + 1] * (255 - a) + bg.G * a) / 255); obuf[i + 2] = (byte)((obuf[i + 2] * (255 - a) + bg.R * a) / 255); } } } Marshal.Copy(obuf, 0, obd.Scan0, obuf.Length); } finally { outBmp.UnlockBits(obd); alphaBmp.UnlockBits(abd2); alphaBmp.Dispose(); } return outBmp; } // ---------------------------------------------------------------- 尺寸 private void GetOutSize(out int w, out int h) { int i = cmbSize.SelectedIndex; if (i < 0) i = 0; w = SIZE_PX[i][0]; h = SIZE_PX[i][1]; } // 计算裁切窗口(原图坐标):先按目标比例缩放到覆盖,再取窗口 private void CropGeom(int outW, int outH, out double cw, out double ch, out double cy) { double s = Math.Max((double)outW / src.Width, (double)outH / src.Height); cw = outW / s; ch = outH / s; if (cw > src.Width) cw = src.Width; if (ch > src.Height) ch = src.Height; double off = (double)numOffset.Value / 200.0; // -0.5 .. 0.5 cy = (src.Height - ch) * (0.5 + off); if (cy < 0) cy = 0; if (cy > src.Height - ch) cy = src.Height - ch; } private Bitmap BuildOutput(string debugPath) { int outW, outH; GetOutSize(out outW, out outH); // 1) 全图换底色(原尺寸) Bitmap full = new Bitmap(src.Width, src.Height, PixelFormat.Format24bppRgb); using (Graphics g = Graphics.FromImage(full)) { g.DrawImage(src, 0, 0, src.Width, src.Height); } // 掩膜在预览尺度上算(快),再放大套用 byte[] pvMask = BuildMask(pv.Width, pv.Height, (int)numTol.Value, true); if (pvMask != null) { if (headless && debugPath != null) DumpMask(pvMask, pv.Width, pv.Height, debugPath + ".mask.png"); byte[] fullMask = UpscaleMask(pvMask, pv.Width, pv.Height, src.Width, src.Height); using (Bitmap composed = ComposeOverlay(full, fullMask, bgColor, (int)numFeather.Value * 2)) { full.Dispose(); full = (Bitmap)composed.Clone(); } } // 2) 裁切 + 缩放到目标尺寸 double cw, ch, cy; CropGeom(outW, outH, out cw, out ch, out cy); double cx = (src.Width - cw) / 2.0; Bitmap res = new Bitmap(outW, outH, PixelFormat.Format24bppRgb); res.SetResolution(300f, 300f); using (Graphics g = Graphics.FromImage(res)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(full, new Rectangle(0, 0, outW, outH), new Rectangle((int)cx, (int)cy, (int)cw, (int)ch), GraphicsUnit.Pixel); } full.Dispose(); return res; } private static void DumpMask(byte[] mask, int w, int h, string path) { try { using (Bitmap mb = new Bitmap(w, h, PixelFormat.Format24bppRgb)) { BitmapData bd = mb.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); byte[] buf = new byte[Math.Abs(bd.Stride) * h]; for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { byte v = mask[y * w + x] == 1 ? (byte)255 : (byte)0; int off = y * bd.Stride + x * 3; buf[off] = v; buf[off + 1] = v; buf[off + 2] = v; } Marshal.Copy(buf, 0, bd.Scan0, buf.Length); mb.UnlockBits(bd); mb.Save(path, ImageFormat.Png); } } catch { } } private static byte[] UpscaleMask(byte[] src, int sw, int sh, int dw, int dh) { byte[] dst = new byte[dw * dh]; for (int y = 0; y < dh; y++) { int sy = y * sh / dh; if (sy >= sh) sy = sh - 1; int srow = sy * sw, drow = y * dw; for (int x = 0; x < dw; x++) { int sx = x * sw / dw; if (sx >= sw) sx = sw - 1; dst[drow + x] = src[srow + sx]; } } return dst; } // ---------------------------------------------------------------- 保存 private void SaveClick(object sender, EventArgs e) { if (src == null) { lblStatus.Text = "请先选择一张照片。"; return; } using (SaveFileDialog d = new SaveFileDialog()) { d.Filter = "JPG 图片|*.jpg"; d.FileName = (Path.GetFileNameWithoutExtension(srcPath).Length > 0 ? Path.GetFileNameWithoutExtension(srcPath) : "证件照") + "_证件照.jpg"; if (d.ShowDialog() != DialogResult.OK) return; try { using (Bitmap outBmp = BuildOutput(null)) { ImageCodecInfo jpeg = GetJpegCodec(); if (jpeg != null) outBmp.Save(d.FileName, jpeg, Q(95)); else outBmp.Save(d.FileName, ImageFormat.Jpeg); } lblStatus.Text = "已保存:" + d.FileName + "(300dpi,可直接去打印或上传报名系统)"; } catch (Exception ex) { MessageBox.Show("保存失败:" + ex.Message, "保存失败", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } // 自测入口 public void LoadForTest(string path) { headless = true; LoadFile(path); } public string SaveForTest(string outPath, int sizeIndex, int tol, int feather) { cmbSize.SelectedIndex = sizeIndex; numTol.Value = tol; numFeather.Value = feather; using (Bitmap outBmp = BuildOutput(outPath)) { ImageCodecInfo jpeg = GetJpegCodec(); if (jpeg != null) outBmp.Save(outPath, jpeg, Q(95)); else outBmp.Save(outPath, ImageFormat.Jpeg); } return outPath; } // 自测:直接指定底色(0 白 / 1 蓝 / 2 红 / 3 浅灰),绕过 UI 下拉框 public void SetBgForTest(int idx) { cmbBg.SelectedIndex = idx; BgChange(null, null); } 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; } protected override void OnFormClosed(FormClosedEventArgs e) { if (src != null) src.Dispose(); if (pv != null) pv.Dispose(); base.OnFormClosed(e); } } // 命令行自测:合成一张「浅蓝底 + 深色人像块」的照片,换三种底色各出一张, // 断言「底真的换了、人像没被吃掉、尺寸对得上」 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 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); } } private static Color Pixel(Image img, int x, int y) { using (Bitmap b = new Bitmap(img)) { if (x >= b.Width) x = b.Width - 1; if (y >= b.Height) y = b.Height - 1; return b.GetPixel(x, y); } } private static string Near(Color got, Color want, int tol) { bool ok = Math.Abs(got.R - want.R) <= tol && Math.Abs(got.G - want.G) <= tol && Math.Abs(got.B - want.B) <= tol; return ok ? "接近" : "偏(" + got.R + "," + got.G + "," + got.B + ")"; } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-idphoto-selftest"); try { if (Directory.Exists(dir)) { try { Directory.Delete(dir, true); } catch { } } Directory.CreateDirectory(dir); _lines.Add("证件照换底色 自测(" + dir + ")"); // 浅蓝底 + 深灰「人像」:底和主体差得够远,容差 40 稳定可分 Color srcBg = Color.FromArgb(205, 222, 242); Color subject = Color.FromArgb(60, 62, 66); string srcPath = Path.Combine(dir, "portrait.png"); using (Bitmap b = new Bitmap(600, 800)) using (Graphics g = Graphics.FromImage(b)) { g.Clear(srcBg); g.FillRectangle(new SolidBrush(subject), 170, 290, 260, 510); b.Save(srcPath, ImageFormat.Png); } IdPhotoForm f = new IdPhotoForm(); f.LoadForTest(srcPath); // ① 红底,一寸 string red = Path.Combine(dir, "red.jpg"); f.SetBgForTest(2); f.SaveForTest(red, 0, 40, 1); Check("红底:产出文件", File.Exists(red) ? "在" : "不在", "在"); using (Image im = Load(red)) { Check("红底:尺寸是一寸 295x413", im.Width + "x" + im.Height, "295x413"); Check("红底:左上角换成红", Near(Pixel(im, 4, 4), Color.FromArgb(215, 0, 15), 26), "接近"); Check("红底:右上角换成红", Near(Pixel(im, im.Width - 5, 4), Color.FromArgb(215, 0, 15), 26), "接近"); Check("红底:人像主体没被吃掉", Near(Pixel(im, im.Width / 2, im.Height - 30), subject, 30), "接近"); } // ② 白底 string white = Path.Combine(dir, "white.jpg"); f.SetBgForTest(0); f.SaveForTest(white, 0, 40, 1); using (Image im = Load(white)) { Check("白底:左上角变白", Near(Pixel(im, 4, 4), Color.White, 12), "接近"); Check("白底:人像主体没被吃掉", Near(Pixel(im, im.Width / 2, im.Height - 30), subject, 30), "接近"); } // ③ 蓝底 + 二寸规格:尺寸要跟着规格变 string blue = Path.Combine(dir, "blue.jpg"); f.SetBgForTest(1); f.SaveForTest(blue, 3, 40, 1); using (Image im = Load(blue)) { Check("蓝底二寸:尺寸 413x579", im.Width + "x" + im.Height, "413x579"); Check("蓝底二寸:左上角换成蓝", Near(Pixel(im, 4, 4), Color.FromArgb(67, 142, 219), 26), "接近"); } // ④ 原图不许被改 using (Image orig = Load(srcPath)) Check("原图没被就地改掉", Near(Pixel(orig, 4, 4), srcBg, 6), "接近"); } 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-idphoto.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // 自测:IdPhotoTool.exe --selftest [工作目录] (退出码 0 全过 / 1 有失败) if (args.Length >= 1 && args[0] == "--selftest") { Environment.Exit(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } // 临时驱动(截图/核对脚本用):--batch <原图> <输出.jpg> [规格序号] [容差] if (args.Length >= 3 && args[0] == "--batch") { int si = args.Length >= 4 ? int.Parse(args[3]) : 0; int tol = args.Length >= 5 ? int.Parse(args[4]) : 40; try { IdPhotoForm f = new IdPhotoForm(); f.LoadForTest(args[1]); f.SaveForTest(args[2], si, tol, 1); Console.WriteLine("saved=" + args[2]); } catch (Exception ex) { Console.WriteLine("ERROR " + ex.GetType().Name + ": " + ex.Message); Console.WriteLine(ex.StackTrace); try { File.WriteAllText(Path.Combine(Path.GetDirectoryName(args[2]), "selftest-error.txt"), ex.ToString()); } catch { } } return; } Application.Run(new IdPhotoForm()); } } }