// 二维码生成 - 绿色工具箱 // C# 5.0 语法。使用 QRCoder(MIT 许可)生成,构建后经 ILMerge 合并为单 exe // 功能:单条/批量(每行一条)生成二维码 PNG,无水印、永不过期、纯本地 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; using QRCoder; namespace GreenToolbox { public class QrCodeToolForm : 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 txtInput; private ComboBox cmbPixels, cmbEcc; private PictureBox preview; private Button btnGen, btnBatch, btnSave; private Label lblStatus; private byte[] lastPng; public QrCodeToolForm() { InitUi(); GeneratePreview(); } 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(700, 520); this.MinimumSize = new Size(620, 480); int x = 20, y = 16; Label l0 = new Label(); l0.Text = "粘贴文本/网址生成二维码。批量模式:一行一条,全部生成 PNG 到所选文件夹"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 30; txtInput = new TextBox(); txtInput.Location = new Point(x, y); txtInput.Size = new Size(420, 300); txtInput.Multiline = true; txtInput.ScrollBars = ScrollBars.Vertical; txtInput.Font = new Font("Consolas", 10f); txtInput.Text = "https://getgreentool.com"; txtInput.TextChanged += new EventHandler(delegate(object s, EventArgs e) { GeneratePreview(); }); this.Controls.Add(txtInput); preview = new PictureBox(); preview.Location = new Point(456, y); preview.Size = new Size(220, 220); preview.BorderStyle = BorderStyle.FixedSingle; preview.SizeMode = PictureBoxSizeMode.Zoom; preview.BackColor = COL_PANEL; this.Controls.Add(preview); Label lp = new Label(); lp.Text = "实时预览"; lp.Location = new Point(456, y + 224); lp.AutoSize = true; lp.ForeColor = COL_GRAY; this.Controls.Add(lp); y += 314; Label l1 = new Label(); l1.Text = "尺寸:"; l1.AutoSize = true; l1.Location = new Point(x, y + 5); this.Controls.Add(l1); cmbPixels = new ComboBox(); cmbPixels.DropDownStyle = ComboBoxStyle.DropDownList; cmbPixels.Items.Add("小(约 120px)"); cmbPixels.Items.Add("中(约 240px)"); cmbPixels.Items.Add("大(约 480px)"); cmbPixels.SelectedIndex = 1; cmbPixels.Location = new Point(x + 44, y + 2); cmbPixels.Size = new Size(140, 26); this.Controls.Add(cmbPixels); Label l2 = new Label(); l2.Text = "容错:"; l2.AutoSize = true; l2.Location = new Point(x + 200, y + 5); this.Controls.Add(l2); cmbEcc = new ComboBox(); cmbEcc.DropDownStyle = ComboBoxStyle.DropDownList; cmbEcc.Items.Add("L(最小,7%可修复)"); cmbEcc.Items.Add("M(推荐,15%)"); cmbEcc.Items.Add("Q(25%)"); cmbEcc.Items.Add("H(最高,30%)"); cmbEcc.SelectedIndex = 1; cmbEcc.Location = new Point(x + 248, y + 2); cmbEcc.Size = new Size(180, 26); this.Controls.Add(cmbEcc); y += 42; btnGen = new Button(); btnGen.Text = "重新生成预览"; btnGen.Location = new Point(x, y); btnGen.Size = new Size(130, 32); btnGen.FlatStyle = FlatStyle.Flat; btnGen.FlatAppearance.BorderColor = COL_GREEN; btnGen.ForeColor = Color.FromArgb(0, 110, 66); btnGen.Click += new EventHandler(delegate(object s, EventArgs e) { GeneratePreview(); }); this.Controls.Add(btnGen); btnSave = new Button(); btnSave.Text = "保存 PNG"; btnSave.Location = new Point(x + 142, y); btnSave.Size = new Size(110, 32); btnSave.FlatStyle = FlatStyle.Flat; btnSave.FlatAppearance.BorderColor = COL_GREEN; btnSave.ForeColor = Color.FromArgb(0, 110, 66); btnSave.Click += new EventHandler(SaveClick); this.Controls.Add(btnSave); btnBatch = new Button(); btnBatch.Text = "批量生成到文件夹"; btnBatch.Location = new Point(x + 264, y); btnBatch.Size = new Size(160, 32); btnBatch.BackColor = COL_GREEN; btnBatch.ForeColor = Color.White; btnBatch.FlatStyle = FlatStyle.Flat; btnBatch.FlatAppearance.BorderSize = 0; btnBatch.Click += new EventHandler(BatchClick); this.Controls.Add(btnBatch); y += 48; lblStatus = new Label(); lblStatus.Text = "无水印、无有效期、不联网。生成的 PNG 可直接印刷。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); } private int PixelsPerModule() { return QrOps.PixelsFor(cmbPixels.SelectedIndex); } private QRCodeGenerator.ECCLevel Ecc() { return QrOps.EccFor(cmbEcc.SelectedIndex); } private byte[] MakePng(string text, int pixelsPerModule, QRCodeGenerator.ECCLevel ecc) { return QrOps.MakePng(text, pixelsPerModule, ecc); } private void GeneratePreview() { string text = txtInput.Lines.Length > 0 ? txtInput.Lines[0] : ""; if (text.Trim().Length == 0) { preview.Image = null; return; } try { lastPng = MakePng(text, PixelsPerModule(), Ecc()); using (MemoryStream ms = new MemoryStream(lastPng)) using (Image img = Image.FromStream(ms)) { Image copy = new Bitmap(img); preview.Image = copy; } } catch (Exception ex) { preview.Image = null; lblStatus.Text = "生成失败:" + ex.Message; } } private void SaveClick(object sender, EventArgs e) { if (lastPng == null) { lblStatus.Text = "先输入内容生成。"; return; } using (SaveFileDialog d = new SaveFileDialog()) { d.Filter = "PNG 图片 (*.png)|*.png"; d.FileName = "二维码.png"; if (d.ShowDialog() == DialogResult.OK) { File.WriteAllBytes(d.FileName, lastPng); lblStatus.Text = "已保存:" + d.FileName; } } } private void BatchClick(object sender, EventArgs e) { List items = new List(); foreach (string line in txtInput.Lines) if (line.Trim().Length > 0) items.Add(line.Trim()); if (items.Count == 0) { lblStatus.Text = "没有可生成的内容。"; return; } using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择保存二维码 PNG 的文件夹"; if (d.ShowDialog() != DialogResult.OK) return; string dir = d.SelectedPath; int ok = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < items.Count; i++) { try { byte[] png = MakePng(items[i], PixelsPerModule(), Ecc()); string path = Path.Combine(dir, QrOps.BatchFileName(i + 1, items[i])); File.WriteAllBytes(path, png); ok++; } catch (Exception ex) { sb.AppendLine(items[i] + " 失败:" + ex.Message); } } lblStatus.Text = "批量完成:" + ok + "/" + items.Count + " 张已保存到 " + dir; if (sb.Length > 0) MessageBox.Show(sb.ToString(), "部分失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } // ── 与界面解耦的纯逻辑,--selftest 直接调这里 ───────────────────────── public static class QrOps { public static readonly int[] PPM = new int[] { 3, 6, 12 }; public static int PixelsFor(int idx) { if (idx < 0 || idx >= PPM.Length) return 6; return PPM[idx]; } public static QRCodeGenerator.ECCLevel EccFor(int idx) { QRCodeGenerator.ECCLevel[] all = new QRCodeGenerator.ECCLevel[] { QRCodeGenerator.ECCLevel.L, QRCodeGenerator.ECCLevel.M, QRCodeGenerator.ECCLevel.Q, QRCodeGenerator.ECCLevel.H }; if (idx < 0 || idx >= all.Length) return QRCodeGenerator.ECCLevel.M; return all[idx]; } public static byte[] MakePng(string text, int pixelsPerModule, QRCodeGenerator.ECCLevel ecc) { using (QRCodeGenerator gen = new QRCodeGenerator()) using (QRCodeData data = gen.CreateQrCode(text, ecc)) using (PngByteQRCode qr = new PngByteQRCode(data)) { return qr.GetGraphic(pixelsPerModule, new byte[] { 0, 0, 0, 255 }, new byte[] { 255, 255, 255, 255 }); } } // 文件名里不能有 : / ? 这些字符,一律换成下划线;太长截断防止路径超限 public static string SafeName(string text, int max) { if (text == null) return ""; string s = text.Length > max ? text.Substring(0, max) : text; char[] bad = Path.GetInvalidFileNameChars(); for (int i = 0; i < bad.Length; i++) s = s.Replace(bad[i], '_'); s = s.Trim(); return s; } public static string BatchFileName(int n, string text) { string s = SafeName(text, 20); if (s.Length == 0) s = "code"; return n.ToString("D3") + "_" + s + ".png"; } public static bool IsPng(byte[] b) { if (b == null || b.Length < 8) return false; byte[] magic = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }; for (int i = 0; i < 8; i++) if (b[i] != magic[i]) return false; return true; } } // 命令行自测:不弹窗,纯逻辑跑一遍,退出码 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()); } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-qr-selftest"); try { Directory.CreateDirectory(dir); _lines.Add("二维码生成 自测(" + dir + ")"); // ── 尺寸档位 ── CheckInt("小档 3 px/模块", QrOps.PixelsFor(0), 3); CheckInt("中档 6 px/模块", QrOps.PixelsFor(1), 6); CheckInt("大档 12 px/模块", QrOps.PixelsFor(2), 12); // ── 容错档位 ── Check("默认是 M 级", QrOps.EccFor(1).ToString(), "M"); Check("最高是 H 级", QrOps.EccFor(3).ToString(), "H"); // ── 生成一张真 PNG ── byte[] png = QrOps.MakePng("https://getgreentool.com", 6, QrOps.EccFor(1)); Check("输出是合法 PNG(文件头 89 50 4E 47)", QrOps.IsPng(png) ? "png" : "not-png", "png"); CheckInt("文件不为空", png.Length > 200 ? 1 : 0, 1); int w, h; using (MemoryStream ms = new MemoryStream(png)) using (Image img = Image.FromStream(ms)) { w = img.Width; h = img.Height; Check("是正方形", w == h ? "square" : "not-square", "square"); Check("宽度是 6 的整数倍(每模块 6 px)", (w % 6).ToString(), "0"); Check("尺寸够扫(至少 100px)", w >= 100 ? "ok" : w.ToString(), "ok"); // 只允许黑/白两种点,不能有灰边(灰边扫不出来) using (Bitmap bmp = new Bitmap(img)) { bool onlyBw = true; for (int y = 0; y < bmp.Height; y += 3) for (int xx = 0; xx < bmp.Width; xx += 3) { Color c = bmp.GetPixel(xx, y); if (Math.Abs(c.R - c.G) > 8 || Math.Abs(c.G - c.B) > 8) { onlyBw = false; break; } if (c.R > 40 && c.R < 215) { onlyBw = false; break; } } Check("只有黑白两色(无灰阶/彩色噪点)", onlyBw ? "bw" : "gray", "bw"); } } // ── 同内容:像素越大图越大 ── byte[] small = QrOps.MakePng("https://getgreentool.com", 3, QrOps.EccFor(1)); int sw, lw; using (MemoryStream ms = new MemoryStream(small)) using (Image i2 = Image.FromStream(ms)) sw = i2.Width; using (MemoryStream ms = new MemoryStream(png)) using (Image i3 = Image.FromStream(ms)) lw = i3.Width; CheckInt("像素密度翻倍,图宽正好翻倍", lw, sw * 2); // ── 容错等级越高,模块越多(图更大)── int wl, wh; byte[] lvL = QrOps.MakePng("https://getgreentool.com/abcdefg", 6, QrOps.EccFor(0)); byte[] lvH = QrOps.MakePng("https://getgreentool.com/abcdefg", 6, QrOps.EccFor(3)); using (MemoryStream ms = new MemoryStream(lvL)) using (Image i4 = Image.FromStream(ms)) wl = i4.Width; using (MemoryStream ms = new MemoryStream(lvH)) using (Image i5 = Image.FromStream(ms)) wh = i5.Width; Check("H 级不比 L 级小(纠错多占空间)", wh >= wl ? "ok" : wh + "<" + wl, "ok"); // ── 中文内容 ── byte[] cjk = QrOps.MakePng("绿色工具箱:离线二维码", 6, QrOps.EccFor(1)); Check("中文内容也能生成", QrOps.IsPng(cjk) ? "png" : "not-png", "png"); // ── 长内容与超限 ── byte[] longText = QrOps.MakePng(new string('a', 900), 3, QrOps.EccFor(0)); Check("900 字符长文本能生成", QrOps.IsPng(longText) ? "png" : "not-png", "png"); bool threw = false; try { QrOps.MakePng(new string('a', 4000), 3, QrOps.EccFor(3)); } catch { threw = true; } Check("超容量内容明确报错(不静默出空图)", threw ? "threw" : "silent", "threw"); // ── 批量文件名 ── Check("序号三位补零 + 内容", QrOps.BatchFileName(7, "abc"), "007_abc.png"); Check("网址里的 : 和 / 换成下划线", QrOps.SafeName("https://a.com/b", 20), "https___a.com_b"); Check("超过 20 字符截断", QrOps.SafeName("0123456789012345678901234567890", 20).Length.ToString(), "20"); Check("内容为空时给个兜底名", QrOps.BatchFileName(1, " "), "001_code.png"); } 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-qrcode.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 QrCodeToolForm()); } } }