// 图片加水印 - 绿色工具箱 // C# 5.0 语法,零依赖(GDI+ 系统组件) // 功能:给整个文件夹的图片批量加文字或 Logo 水印,可选九宫格位置或满屏平铺, // 可调字号、颜色、透明度、旋转角度,输出到"加水印"子文件夹,不动原图。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using System.IO; using System.Text; using System.Windows.Forms; namespace GreenToolbox { public class WatermarkForm : 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 rbText, rbLogo; private TextBox txtText; private CheckBox chkBold; private Button btnColor, btnLogo; private Label lblLogo; private NumericUpDown numSize, numAngle; private TrackBar barOpacity; private Label lblOpacity; private ComboBox cmbPos; private CheckBox chkSub, chkForceJpg; private Button btnRun; private ProgressBar progress; private Label lblStatus; private PictureBox pic; private BackgroundWorker worker; private Color curColor = Color.FromArgb(255, 255, 255); private Image logoImg = null; private string logoPath = ""; private Image previewSrc = null; private string previewPath = ""; public WatermarkForm() { 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(900, 660); this.MinimumSize = new Size(900, 660); 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(390, 26); txtFolder.ReadOnly = true; txtFolder.BackColor = COL_PANEL; this.Controls.Add(txtFolder); Button btnBrowse = Flat("浏览文件夹", new Point(418, 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(514, 150); g1.ForeColor = COL_GREEN; g1.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g1); rbText = new RadioButton(); rbText.Text = "文字"; rbText.Location = new Point(14, 26); rbText.AutoSize = true; rbText.Checked = true; rbText.ForeColor = this.ForeColor; rbText.Font = this.Font; rbText.CheckedChanged += new EventHandler(OnKindChange); g1.Controls.Add(rbText); rbLogo = new RadioButton(); rbLogo.Text = "Logo 图片"; rbLogo.Location = new Point(88, 26); rbLogo.AutoSize = true; rbLogo.ForeColor = this.ForeColor; rbLogo.Font = this.Font; rbLogo.CheckedChanged += new EventHandler(OnKindChange); g1.Controls.Add(rbLogo); chkBold = new CheckBox(); chkBold.Text = "加粗"; chkBold.Location = new Point(420, 26); chkBold.AutoSize = true; chkBold.Checked = true; chkBold.ForeColor = this.ForeColor; chkBold.Font = this.Font; chkBold.CheckedChanged += new EventHandler(AnyChange); g1.Controls.Add(chkBold); txtText = new TextBox(); txtText.Location = new Point(14, 56); txtText.Size = new Size(336, 26); txtText.Text = "仅供参考"; txtText.TextChanged += new EventHandler(AnyChange); g1.Controls.Add(txtText); Label lc = new Label(); lc.Text = "颜色"; lc.AutoSize = true; lc.ForeColor = COL_GRAY; lc.Location = new Point(12, 96); lc.Font = this.Font; g1.Controls.Add(lc); btnColor = Flat("■ 白色", new Point(58, 90), new Size(90, 30), false); btnColor.ForeColor = Color.FromArgb(60, 66, 62); btnColor.Click += new EventHandler(PickColor); g1.Controls.Add(btnColor); Label ls = new Label(); ls.Text = "字号"; ls.AutoSize = true; ls.ForeColor = COL_GRAY; ls.Location = new Point(168, 96); ls.Font = this.Font; g1.Controls.Add(ls); numSize = new NumericUpDown(); numSize.Location = new Point(212, 92); numSize.Size = new Size(58, 26); numSize.Minimum = 1; numSize.Maximum = 40; numSize.Value = 6; numSize.ValueChanged += new EventHandler(AnyChange); g1.Controls.Add(numSize); Label ls2 = new Label(); ls2.Text = "占图片宽度的百分比"; ls2.AutoSize = true; ls2.ForeColor = COL_GRAY; ls2.Location = new Point(276, 96); ls2.Font = this.Font; g1.Controls.Add(ls2); btnLogo = Flat("选择图片…", new Point(14, 56), new Size(110, 28), false); btnLogo.Visible = false; btnLogo.Click += new EventHandler(PickLogo); g1.Controls.Add(btnLogo); lblLogo = new Label(); lblLogo.Text = ""; lblLogo.AutoSize = true; lblLogo.ForeColor = COL_GRAY; lblLogo.Location = new Point(134, 62); lblLogo.Font = this.Font; g1.Controls.Add(lblLogo); y += 162; // ---------------- 样式 ---------------- GroupBox g2 = new GroupBox(); g2.Text = "位置与样式"; g2.Location = new Point(x, y); g2.Size = new Size(514, 178); g2.ForeColor = COL_GREEN; g2.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g2); Label lp = new Label(); lp.Text = "位置"; lp.AutoSize = true; lp.ForeColor = COL_GRAY; lp.Location = new Point(14, 30); lp.Font = this.Font; g2.Controls.Add(lp); cmbPos = new ComboBox(); cmbPos.DropDownStyle = ComboBoxStyle.DropDownList; cmbPos.Location = new Point(58, 26); cmbPos.Size = new Size(150, 26); cmbPos.Items.AddRange(new object[] { "右下角(默认)", "左下角", "右上角", "左上角", "正中", "上中", "下中", "左中", "右中", "满屏平铺" }); cmbPos.SelectedIndex = 0; cmbPos.SelectedIndexChanged += new EventHandler(AnyChange); g2.Controls.Add(cmbPos); Label la = new Label(); la.Text = "角度"; la.AutoSize = true; la.ForeColor = COL_GRAY; la.Location = new Point(228, 30); la.Font = this.Font; g2.Controls.Add(la); numAngle = new NumericUpDown(); numAngle.Location = new Point(272, 26); numAngle.Size = new Size(58, 26); numAngle.Minimum = -90; numAngle.Maximum = 90; numAngle.Value = 0; numAngle.ValueChanged += new EventHandler(AnyChange); g2.Controls.Add(numAngle); Label la2 = new Label(); la2.Text = "度(平铺常配 -30)"; la2.AutoSize = true; la2.ForeColor = COL_GRAY; la2.Location = new Point(336, 30); la2.Font = this.Font; g2.Controls.Add(la2); Label lo = new Label(); lo.Text = "不透明度"; lo.AutoSize = true; lo.ForeColor = COL_GRAY; lo.Location = new Point(14, 74); lo.Font = this.Font; g2.Controls.Add(lo); barOpacity = new TrackBar(); barOpacity.Minimum = 5; barOpacity.Maximum = 100; barOpacity.Value = 45; barOpacity.Location = new Point(92, 66); barOpacity.Size = new Size(330, 40); barOpacity.TickFrequency = 10; barOpacity.ValueChanged += new EventHandler(AnyChange); g2.Controls.Add(barOpacity); lblOpacity = new Label(); lblOpacity.Text = "45%"; lblOpacity.AutoSize = true; lblOpacity.Location = new Point(428, 74); lblOpacity.ForeColor = COL_GRAY; lblOpacity.Font = this.Font; g2.Controls.Add(lblOpacity); chkSub = new CheckBox(); chkSub.Text = "包含子文件夹"; chkSub.Location = new Point(16, 122); chkSub.AutoSize = true; chkSub.ForeColor = this.ForeColor; chkSub.Font = this.Font; g2.Controls.Add(chkSub); chkForceJpg = new CheckBox(); chkForceJpg.Text = "统一输出为 JPG(体积更小)"; chkForceJpg.Location = new Point(150, 122); chkForceJpg.AutoSize = true; chkForceJpg.ForeColor = this.ForeColor; chkForceJpg.Font = this.Font; g2.Controls.Add(chkForceJpg); y += 190; btnRun = new Button(); btnRun.Text = "开始加水印"; btnRun.Location = new Point(x, y); btnRun.Size = new Size(140, 36); 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 + 48); progress.Size = new Size(514, 8); this.Controls.Add(progress); lblStatus = new Label(); lblStatus.Text = "不联网、不上传,全部在本机完成。"; lblStatus.Location = new Point(x, y + 62); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); // ---------------- 预览 ---------------- GroupBox g3 = new GroupBox(); g3.Text = "效果预览(第一张图)"; g3.Location = new Point(552, 30); g3.Size = new Size(328, 596); g3.ForeColor = COL_GREEN; g3.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g3); pic = new PictureBox(); pic.Location = new Point(10, 26); pic.Size = new Size(306, 556); pic.BackColor = COL_PANEL; pic.SizeMode = PictureBoxSizeMode.Normal; pic.BorderStyle = BorderStyle.FixedSingle; g3.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; 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 OnKindChange(object sender, EventArgs e) { bool isText = rbText.Checked; txtText.Visible = isText; chkBold.Visible = isText; btnLogo.Visible = !isText; lblLogo.Visible = !isText; lblLogo.Text = logoPath.Length == 0 ? "(还没选图片)" : Path.GetFileName(logoPath); RenderPreview(); } 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 "红色"; if (c.R > 200 && c.G > 200 && c.B < 90) return "黄色"; return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"); } private void PickLogo(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Filter = "图片|*.png;*.jpg;*.jpeg;*.bmp;*.gif"; d.Title = "选择 Logo 图片(建议用透明背景的 PNG)"; if (d.ShowDialog() == DialogResult.OK) { try { if (logoImg != null) logoImg.Dispose(); logoImg = LoadPic(d.FileName); logoPath = d.FileName; lblLogo.Text = Path.GetFileName(logoPath); RenderPreview(); } catch (Exception ex) { MessageBox.Show("这个图片打不开:" + ex.Message, "打不开", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } } private void AnyChange(object sender, EventArgs e) { if (lblOpacity != null) lblOpacity.Text = barOpacity.Value + "%"; RenderPreview(); } // ---------------------------------------------------------------- 预览 private void LoadPreview() { string folder = txtFolder.Text; if (folder.Length == 0 || !Directory.Exists(folder)) return; List files = Collect(folder, false); if (files.Count == 0) { lblStatus.Text = "这个文件夹里没有 jpg/png/bmp 图片。"; if (previewSrc != null) { previewSrc.Dispose(); previewSrc = null; } pic.Image = null; return; } try { if (previewSrc != null) previewSrc.Dispose(); previewSrc = LoadPic(files[0]); previewPath = files[0]; lblStatus.Text = "共 " + files.Count + " 张图片,预览:" + Path.GetFileName(previewPath); 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; Bitmap bmp = new Bitmap(pw, ph); using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(COL_PANEL); g.InterpolationMode = InterpolationMode.HighQualityBicubic; float s = Math.Min((float)pw / previewSrc.Width, (float)ph / previewSrc.Height); if (s > 1f) s = 1f; int dw = (int)(previewSrc.Width * s), dh = (int)(previewSrc.Height * s); int dx = (pw - dw) / 2, dy = (ph - dh) / 2; g.DrawImage(previewSrc, dx, dy, dw, dh); GraphicsState st = g.Save(); g.TranslateTransform(dx, dy); g.ScaleTransform(s, s); DrawMark(g, previewSrc.Width, previewSrc.Height); g.Restore(st); } Image old = pic.Image; pic.Image = bmp; if (old != null && old != previewSrc) old.Dispose(); } // ---------------------------------------------------------------- 绘制 private Font MakeFont(int imgW) { float px = imgW * (float)numSize.Value / 100f; if (px < 8f) px = 8f; FontStyle st = chkBold.Checked ? FontStyle.Bold : FontStyle.Regular; string[] prefer = new string[] { "Microsoft YaHei UI", "Microsoft YaHei", "SimHei", "Arial" }; foreach (string fn in prefer) { try { Font f = new Font(fn, px, st, GraphicsUnit.Pixel); if (f.Name.Length > 0) return f; } catch { } } return new Font(FontFamily.GenericSansSerif, px, st, GraphicsUnit.Pixel); } private void DrawMark(Graphics g, int w, int h) { g.SmoothingMode = SmoothingMode.AntiAlias; g.TextRenderingHint = TextRenderingHint.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; int alpha = (int)(barOpacity.Value * 255 / 100); int pos = cmbPos.SelectedIndex < 0 ? 0 : cmbPos.SelectedIndex; float angle = (float)numAngle.Value; if (rbText.Checked) { string txt = txtText.Text; if (txt.Trim().Length == 0) return; using (Font f = MakeFont(w)) using (SolidBrush br = new SolidBrush(Color.FromArgb(alpha, curColor))) { if (pos == 9) DrawTiledText(g, txt, f, br, w, h, angle); else DrawPlacedText(g, txt, f, br, w, h, pos, angle); } } else { if (logoImg == null) return; int lw = (int)(w * (float)numSize.Value / 100f); if (lw < 8) lw = 8; int lh = (int)((long)logoImg.Height * lw / logoImg.Width); if (lh < 1) lh = 1; ColorMatrix cm = new ColorMatrix(); cm.Matrix33 = barOpacity.Value / 100f; ImageAttributes ia = new ImageAttributes(); ia.SetColorMatrix(cm, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); try { if (pos == 9) DrawTiledLogo(g, ia, lw, lh, w, h, angle); else DrawPlacedLogo(g, ia, lw, lh, w, h, pos, angle); } finally { ia.Dispose(); } } } private SizeF MeasureText(Graphics g, string txt, Font f) { SizeF s = g.MeasureString(txt, f, PointF.Empty, StringFormat.GenericTypographic); // 旋转字距时多留一点,避免挨得太紧 return new SizeF(s.Width + 1f, s.Height); } private void DrawPlacedText(Graphics g, string txt, Font f, Brush br, int w, int h, int pos, float angle) { SizeF ts = MeasureText(g, txt, f); float m = w * 0.03f; float tw = ts.Width, th = ts.Height; float x, y; int col = pos % 3, row = pos / 3; if (col == 0) x = m; else if (col == 1) x = (w - tw) / 2f; else x = w - tw - m; if (row == 0) y = m; else if (row == 1) y = (h - th) / 2f; else y = h - th - m; GraphicsState st = g.Save(); if (angle != 0f) { g.TranslateTransform(x + tw / 2f, y + th / 2f); g.RotateTransform(angle); g.DrawString(txt, f, br, -tw / 2f, -th / 2f, StringFormat.GenericTypographic); } else { g.DrawString(txt, f, br, x, y, StringFormat.GenericTypographic); } g.Restore(st); } private void DrawTiledText(Graphics g, string txt, Font f, Brush br, int w, int h, float angle) { SizeF ts = MeasureText(g, txt, f); float stepX = ts.Width + w * 0.08f; float stepY = ts.Height + h * 0.06f; if (stepX < 40f) stepX = 40f; if (stepY < 30f) stepY = 30f; double diag = Math.Sqrt((double)w * w + (double)h * h); float half = (float)diag / 2f + Math.Max(stepX, stepY); GraphicsState st = g.Save(); g.TranslateTransform(w / 2f, h / 2f); g.RotateTransform(angle == 0f ? -30f : angle); for (float yy = -half; yy <= half; yy += stepY) { for (float xx = -half; xx <= half; xx += stepX) { g.DrawString(txt, f, br, xx, yy, StringFormat.GenericTypographic); } } g.Restore(st); } private void DrawPlacedLogo(Graphics g, ImageAttributes ia, int lw, int lh, int w, int h, int pos, float angle) { float m = w * 0.03f; float x, y; int col = pos % 3, row = pos / 3; if (col == 0) x = m; else if (col == 1) x = (w - lw) / 2f; else x = w - lw - m; if (row == 0) y = m; else if (row == 1) y = (h - lh) / 2f; else y = h - lh - m; GraphicsState st = g.Save(); if (angle != 0f) { g.TranslateTransform(x + lw / 2f, y + lh / 2f); g.RotateTransform(angle); g.DrawImage(logoImg, new Rectangle(-lw / 2, -lh / 2, lw, lh), 0, 0, logoImg.Width, logoImg.Height, GraphicsUnit.Pixel, ia); } else { g.DrawImage(logoImg, new Rectangle((int)x, (int)y, lw, lh), 0, 0, logoImg.Width, logoImg.Height, GraphicsUnit.Pixel, ia); } g.Restore(st); } private void DrawTiledLogo(Graphics g, ImageAttributes ia, int lw, int lh, int w, int h, float angle) { float stepX = lw + w * 0.08f; float stepY = lh + h * 0.06f; if (stepX < 40f) stepX = 40f; if (stepY < 30f) stepY = 30f; double diag = Math.Sqrt((double)w * w + (double)h * h); float half = (float)diag / 2f + Math.Max(stepX, stepY); GraphicsState st = g.Save(); g.TranslateTransform(w / 2f, h / 2f); g.RotateTransform(angle == 0f ? -30f : angle); for (float yy = -half; yy <= half; yy += stepY) { for (float xx = -half; xx <= half; xx += stepX) { g.DrawImage(logoImg, new Rectangle((int)xx, (int)yy, lw, lh), 0, 0, logoImg.Width, logoImg.Height, GraphicsUnit.Pixel, ia); } } g.Restore(st); } // ---------------------------------------------------------------- 批量处理 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 (rbText.Checked && txtText.Text.Trim().Length == 0) { lblStatus.Text = "水印文字不能为空。"; return; } if (!rbText.Checked && logoImg == null) { lblStatus.Text = "还没选择 Logo 图片。"; 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); 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); DrawMark(g, img.Width, img.Height); } if (outPath.ToLower().EndsWith(".png")) { bmp.Save(outPath, ImageFormat.Png); } else if (jpeg != null) { bmp.Save(outPath, jpeg, Q(92)); } else { bmp.Save(outPath, ImageFormat.Jpeg); } } 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 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(); if (logoImg != null) logoImg.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 SetForTest(string text, int pos, int opacity, int angle, int sizePct, bool tiled) { rbText.Checked = true; txtText.Text = text; cmbPos.SelectedIndex = pos; barOpacity.Value = opacity; numAngle.Value = angle; numSize.Value = sizePct; if (tiled) cmbPos.SelectedIndex = 9; lblOpacity.Text = barOpacity.Value + "%"; } // 默认字色是白色(白字压照片最常见),白底图上会看不见; // 自测要能指定颜色,否则断不出「画没画上去」 public void SetColorForTest(Color c) { curColor = c; btnColor.Text = "■ " + NameOf(curColor); } } // 命令行自测:白底图各画一遍水印,断言「该有字的地方有字、不该有的地方干净、原图没被改」 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 CheckMore(string name, int got, int floor) { if (got > floor) { _pass++; _lines.Add(" [ok] " + name + "(" + got + ")"); } else { _fail++; _lines.Add(" [!!] " + name + " 期望>" + floor + " 实际[" + 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); } } // 统计某块区域里「不是接近纯白」的像素数:水印压在白底上就是这个特征 private static int InkIn(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; x++) { Color c = b.GetPixel(x, y); if (c.R < 240 || c.G < 240 || c.B < 240) n++; } return n; } } private static string NewCase(string root, string name) { string d = Path.Combine(root, name); Directory.CreateDirectory(d); using (Bitmap b = new Bitmap(400, 300)) using (Graphics g = Graphics.FromImage(b)) { g.Clear(Color.White); b.Save(Path.Combine(d, "shot.png"), ImageFormat.Png); } return d; } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-watermark-selftest"); try { if (Directory.Exists(dir)) { try { Directory.Delete(dir, true); } catch { } } Directory.CreateDirectory(dir); _lines.Add("图片加水印 自测(" + dir + ")"); string c1 = NewCase(dir, "center"); string c2 = NewCase(dir, "tiled"); string c3 = NewCase(dir, "corner"); string src1 = Path.Combine(c1, "shot.png"); byte[] srcBytes = File.ReadAllBytes(src1); WatermarkForm f = new WatermarkForm(); // ① 正中一枚,100% 不透明:正中有字,四角干净 f.SetForTest("仅供参考", 4, 100, 0, 20, false); f.SetColorForTest(Color.FromArgb(200, 30, 30)); object[] r1 = f.RunBatch(c1); CheckInt("正中水印:处理 1 张", (int)r1[1], 1); CheckInt("正中水印:失败 0 张", (int)r1[2], 0); string o1 = Path.Combine(c1, "加水印", "shot.png"); Check("正中水印:png 进来还是 png 出去", File.Exists(o1) ? "在" : "不在", "在"); using (Image im1 = Load(o1)) { Check("正中水印:尺寸没变", im1.Width + "x" + im1.Height, "400x300"); CheckMore("正中水印:画面中间有字", InkIn(im1, 100, 100, 300, 200), 100); CheckInt("正中水印:左上角还是白的", InkIn(im1, 0, 0, 40, 40), 0); CheckInt("正中水印:右下角还是白的", InkIn(im1, 360, 260, 400, 300), 0); } // ② 平铺:字的像素量应当明显多于单枚 f.SetForTest("仅供参考", 9, 100, -30, 20, true); f.SetColorForTest(Color.FromArgb(200, 30, 30)); object[] r2 = f.RunBatch(c2); CheckInt("平铺水印:处理 1 张", (int)r2[1], 1); string o2 = Path.Combine(c2, "加水印", "shot.png"); int inkTiled = 0, inkOne = 0; using (Image im2 = Load(o2)) inkTiled = InkIn(im2, 0, 0, 400, 300); using (Image im1b = Load(o1)) inkOne = InkIn(im1b, 0, 0, 400, 300); CheckMore("平铺水印:铺满全图(墨量远多于单枚)", inkTiled, inkOne * 2); // ③ 左上角对齐 + 半透明:角上有字,但比 100% 时浅 f.SetForTest("仅供参考", 0, 100, 0, 20, false); f.SetColorForTest(Color.FromArgb(200, 30, 30)); object[] r3 = f.RunBatch(c3); CheckInt("左上水印:处理 1 张", (int)r3[1], 1); string o3 = Path.Combine(c3, "加水印", "shot.png"); Check("左上水印:产出文件", File.Exists(o3) ? "在" : "不在", "在"); using (Image im3 = Load(o3)) { CheckMore("左上水印:左上角有字", InkIn(im3, 0, 0, 200, 100), 50); CheckInt("左上水印:右下角没字", InkIn(im3, 300, 200, 400, 300), 0); } // ④ 源图不许被改(加水印最容易犯的错就是原地覆盖) byte[] after = File.ReadAllBytes(src1); bool same = srcBytes.Length == after.Length; if (same) { for (int i = 0; i < after.Length; i++) if (after[i] != srcBytes[i]) { same = false; break; } } Check("源图没被就地改掉", same ? "一致" : "被改", "一致"); // ⑤ 空文件夹不炸 string empty = Path.Combine(dir, "empty"); Directory.CreateDirectory(empty); object[] r5 = f.RunBatch(empty); CheckInt("空文件夹:处理 0 张", (int)r5[1], 0); CheckInt("空文件夹:不报失败", (int)r5[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-watermark.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); // 自测:WatermarkTool.exe --selftest [工作目录] (退出码 0 全过 / 1 有失败) if (args.Length >= 1 && args[0] == "--selftest") { Environment.Exit(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } // 临时驱动(截图/核对脚本用):--batch <图片文件夹> [tiled] if (args.Length >= 2 && args[0] == "--batch") { WatermarkForm f = new WatermarkForm(); bool tiled = args.Length >= 3 && args[2] == "tiled"; f.SetForTest("仅供参考", tiled ? 9 : 0, 45, tiled ? -30 : 0, 6, tiled); object[] r = f.RunBatch(args[1]); Console.WriteLine("files=" + r[0] + " ok=" + r[1] + " fail=" + r[2] + " out=" + r[3]); return; } Application.Run(new WatermarkForm()); } } }