// 长图拼接(聊天记录/截图拼成一张长图) // 纵向/横向拼接、对齐、间距、背景、统一宽度,全部本地 GDI+ 实现,零依赖。 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using System.IO; using System.Text; using System.Windows.Forms; namespace GtStitch { /* ───────────── 核心:拼接操作 ───────────── */ public static class StitchOps { /* 自然排序:img2 < img10 */ public static int NaturalCompare(string a, string b) { int ia = 0, ib = 0; while (ia < a.Length && ib < b.Length) { char ca = a[ia], cb = b[ib]; if (char.IsDigit(ca) && char.IsDigit(cb)) { long na = 0, nb = 0; int sa = ia, sb = ib; while (ia < a.Length && char.IsDigit(a[ia])) { na = na * 10 + (a[ia] - '0'); ia++; } while (ib < b.Length && char.IsDigit(b[ib])) { nb = nb * 10 + (b[ib] - '0'); ib++; } if (na != nb) return na < nb ? -1 : 1; if (ia - sa != ib - sb) return (ia - sa) < (ib - sb) ? -1 : 1; // 前导零多的在后 } else { if (ca != cb) return ca < cb ? -1 : 1; ia++; ib++; } } return (a.Length - ia) - (b.Length - ib); } public static void NaturalSort(List files) { files.Sort(NaturalCompare); } /* 目标宽度:0 = 保持原尺寸;>0 = 每张等比缩放到该宽 */ public static int ScaledHeight(int w, int h, int targetW) { if (targetW <= 0 || w <= 0) return h; return Math.Max(1, (int)Math.Round((double)h * targetW / w)); } public static int ScaledWidth(int w, int h, int targetH) { if (targetH <= 0 || h <= 0) return w; return Math.Max(1, (int)Math.Round((double)w * targetH / h)); } static Bitmap ScaleTo(Bitmap src, int tw, int th) { if (src.Width == tw && src.Height == th) return src; Bitmap scaled = new Bitmap(tw, th, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(scaled)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(src, new Rectangle(0, 0, tw, th)); } return scaled; } static Color BgOf(string bgName) { switch (bgName) { case "black": return Color.Black; case "transparent": return Color.Transparent; default: return Color.White; } } /* 拼接主函数 mode: "v" 纵向 / "h" 横向 gap: 图间距像素 align: 纵向时 left/center/right;横向时 top/middle/bottom target: 纵向=统一宽度(0=原尺寸),横向=统一高度(0=原尺寸) */ public static Bitmap Render(List imgs, string mode, int gap, string align, int target) { if (imgs == null || imgs.Count == 0) throw new ArgumentException("没有可拼接的图片"); if (gap < 0) gap = 0; List scaled = new List(); List owned = new List(); try { foreach (Bitmap b in imgs) { if (mode == "v") { int tw = target > 0 ? target : b.Width; int th = ScaledHeight(b.Width, b.Height, tw); Bitmap s = ScaleTo(b, tw, th); scaled.Add(s); owned.Add(s != b); } else { int th = target > 0 ? target : b.Height; int tw = ScaledWidth(b.Width, b.Height, th); Bitmap s = ScaleTo(b, tw, th); scaled.Add(s); owned.Add(s != b); } } int n = scaled.Count; int cw, ch; if (mode == "v") { cw = 0; ch = gap * (n - 1); foreach (Bitmap b in scaled) { cw = Math.Max(cw, b.Width); ch += b.Height; } } else { ch = 0; cw = gap * (n - 1); foreach (Bitmap b in scaled) { ch = Math.Max(ch, b.Height); cw += b.Width; } } Bitmap canvas = new Bitmap(Math.Max(1, cw), Math.Max(1, ch), PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(canvas)) { g.Clear(BgOf(mode == "v" ? "transparent" : "transparent")); // 背景色只在用户选了不透明时填充;透明背景交给 PNG alpha int pos = 0; for (int i = 0; i < n; i++) { Bitmap b = scaled[i]; int x, y; if (mode == "v") { y = pos; if (align == "center") x = (cw - b.Width) / 2; else if (align == "right") x = cw - b.Width; else x = 0; } else { x = pos; if (align == "middle") y = (ch - b.Height) / 2; else if (align == "bottom") y = ch - b.Height; else y = 0; } g.DrawImage(b, x, y); pos += (mode == "v" ? b.Height : b.Width) + gap; } } return canvas; } finally { for (int i = 0; i < scaled.Count; i++) if (owned[i]) scaled[i].Dispose(); } } /* 透明背景会让 JPEG 全黑,统一在这里决定底色 */ public static Bitmap Flatten(Bitmap src, string bgName) { if (bgName == "transparent") return src; Bitmap flat = new Bitmap(src.Width, src.Height, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(flat)) { g.Clear(BgOf(bgName)); g.DrawImage(src, 0, 0); } src.Dispose(); return flat; } public static string NextName(string dir) { string stamp = DateTime.Now.ToString("yyyyMMdd-HHmmss"); string p = Path.Combine(dir, "长图-" + stamp + ".png"); int n = 2; while (File.Exists(p)) p = Path.Combine(dir, "长图-" + stamp + "-" + n++ + ".png"); return p; } public static string DefaultOutDir() { string p = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "长图拼接"); if (!Directory.Exists(p)) Directory.CreateDirectory(p); return p; } } /* ───────────── 主窗口 ───────────── */ public class StitchForm : Form { ListView list; RadioButton rbV, rbH; ComboBox cmbAlign; NumericUpDown numGap, numTarget; CheckBox chkTarget; Button btnColor; Label lblStatus; Color bgColor = Color.White; public StitchForm() { Text = "长图拼接 - 绿色工具箱"; Font = new Font("Microsoft YaHei", 9F); StartPosition = FormStartPosition.CenterScreen; Size = new Size(560, 560); AllowDrop = true; DragEnter += (s, e) => { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; DragDrop += (s, e) => AddFiles((string[])e.Data.GetData(DataFormats.FileDrop)); Label tip = new Label(); tip.Text = "把图片拖进来(自动按文件名排序),拼成一张长图"; tip.ForeColor = Color.FromArgb(90, 100, 95); tip.Location = new Point(16, 12); tip.AutoSize = true; Controls.Add(tip); list = new ListView(); list.View = View.Details; list.Columns.Add("顺序", 50); list.Columns.Add("文件名", 300); list.Columns.Add("尺寸", 130); list.FullRowSelect = true; list.HeaderStyle = ColumnHeaderStyle.Nonclickable; list.Location = new Point(16, 38); list.Size = new Size(500, 220); list.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; Controls.Add(list); Button btnAdd = new Button(); btnAdd.Text = "添加图片"; btnAdd.Location = new Point(16, 266); btnAdd.Size = new Size(88, 28); btnAdd.Click += (s, e) => { using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.Title = "选择图片(可多选)"; dlg.Filter = "图片|*.png;*.jpg;*.jpeg;*.bmp;*.gif|全部文件|*.*"; dlg.Multiselect = true; if (dlg.ShowDialog() == DialogResult.OK) AddFiles(dlg.FileNames); } }; Controls.Add(btnAdd); Button btnUp = new Button(); btnUp.Text = "上移"; btnUp.Location = new Point(112, 266); btnUp.Size = new Size(56, 28); btnUp.Click += (s, e) => MoveItem(-1); Controls.Add(btnUp); Button btnDown = new Button(); btnDown.Text = "下移"; btnDown.Location = new Point(174, 266); btnDown.Size = new Size(56, 28); btnDown.Click += (s, e) => MoveItem(1); Controls.Add(btnDown); Button btnRemove = new Button(); btnRemove.Text = "移除选中"; btnRemove.Location = new Point(238, 266); btnRemove.Size = new Size(88, 28); btnRemove.Click += (s, e) => { if (list.SelectedItems.Count > 0) list.SelectedItems[0].Remove(); }; Controls.Add(btnRemove); Button btnClear = new Button(); btnClear.Text = "清空"; btnClear.Location = new Point(334, 266); btnClear.Size = new Size(56, 28); btnClear.Click += (s, e) => list.Items.Clear(); Controls.Add(btnClear); rbV = new RadioButton(); rbV.Text = "纵向(上下)"; rbV.Checked = true; rbV.Location = new Point(16, 306); rbV.AutoSize = true; rbV.CheckedChanged += (s, e) => UpdateAlignItems(); Controls.Add(rbV); rbH = new RadioButton(); rbH.Text = "横向(左右)"; rbH.Location = new Point(130, 306); rbH.AutoSize = true; Controls.Add(rbH); Label lblAlign = new Label(); lblAlign.Text = "对齐"; lblAlign.Location = new Point(250, 308); lblAlign.AutoSize = true; Controls.Add(lblAlign); cmbAlign = new ComboBox(); cmbAlign.DropDownStyle = ComboBoxStyle.DropDownList; cmbAlign.Location = new Point(288, 304); cmbAlign.Width = 90; cmbAlign.Items.AddRange(new object[] { "居左", "居中", "居右" }); cmbAlign.SelectedIndex = 0; Controls.Add(cmbAlign); Label lblGap = new Label(); lblGap.Text = "间距"; lblGap.Location = new Point(396, 308); lblGap.AutoSize = true; Controls.Add(lblGap); numGap = new NumericUpDown(); numGap.Minimum = 0; numGap.Maximum = 500; numGap.Value = 0; numGap.Location = new Point(436, 304); numGap.Width = 80; Controls.Add(numGap); chkTarget = new CheckBox(); chkTarget.Text = "统一宽度"; chkTarget.Location = new Point(16, 344); chkTarget.AutoSize = true; Controls.Add(chkTarget); numTarget = new NumericUpDown(); numTarget.Minimum = 16; numTarget.Maximum = 20000; numTarget.Value = 720; numTarget.Enabled = false; numTarget.Location = new Point(96, 340); numTarget.Width = 90; chkTarget.CheckedChanged += (s, e) => numTarget.Enabled = chkTarget.Checked; Controls.Add(numTarget); Label lblBg = new Label(); lblBg.Text = "背景"; lblBg.Location = new Point(200, 344); lblBg.AutoSize = true; Controls.Add(lblBg); btnColor = new Button(); btnColor.Text = "白色"; btnColor.Location = new Point(238, 339); btnColor.Size = new Size(64, 26); btnColor.Click += (s, e) => { if (bgColor == Color.White) { bgColor = Color.Black; btnColor.Text = "黑色"; } else if (bgColor == Color.Black) { bgColor = Color.Transparent; btnColor.Text = "透明"; } else { bgColor = Color.White; btnColor.Text = "白色"; } }; Controls.Add(btnColor); Button btnGo = new Button(); btnGo.Text = "拼接并保存"; btnGo.Location = new Point(16, 380); btnGo.Size = new Size(160, 34); btnGo.BackColor = Color.FromArgb(64, 156, 255); btnGo.ForeColor = Color.White; btnGo.FlatStyle = FlatStyle.Flat; btnGo.Click += (s, e) => DoStitch(); Controls.Add(btnGo); lblStatus = new Label(); lblStatus.Text = "输出目录:" + StitchOps.DefaultOutDir(); lblStatus.ForeColor = Color.FromArgb(120, 130, 124); lblStatus.Location = new Point(16, 424); lblStatus.AutoSize = true; Controls.Add(lblStatus); Icon = MakeIcon(); } void UpdateAlignItems() { int sel = cmbAlign.SelectedIndex < 0 ? 0 : cmbAlign.SelectedIndex; cmbAlign.Items.Clear(); if (rbV.Checked) cmbAlign.Items.AddRange(new object[] { "居左", "居中", "居右" }); else cmbAlign.Items.AddRange(new object[] { "居上", "居中", "居下" }); cmbAlign.SelectedIndex = sel; } static Icon MakeIcon() { using (Bitmap b = new Bitmap(32, 32)) using (Graphics g = Graphics.FromImage(b)) { g.Clear(Color.Transparent); using (Pen pen = new Pen(Color.FromArgb(64, 156, 255), 3)) { g.DrawRectangle(pen, 3, 2, 26, 12); g.DrawRectangle(pen, 3, 18, 26, 12); } return Icon.FromHandle(b.GetHicon()); } } void AddFiles(string[] paths) { List imgs = new List(); foreach (string p in paths) { if (Directory.Exists(p)) { foreach (string f in Directory.GetFiles(p)) if (IsImage(f)) imgs.Add(f); } else if (IsImage(p)) imgs.Add(p); } StitchOps.NaturalSort(imgs); foreach (string f in imgs) { bool exists = false; foreach (ListViewItem it in list.Items) if (string.Equals((string)it.Tag, f, StringComparison.OrdinalIgnoreCase)) { exists = true; break; } if (exists) continue; try { using (Image img = Image.FromFile(f)) { ListViewItem it = new ListViewItem((list.Items.Count + 1).ToString()); it.SubItems.Add(Path.GetFileName(f)); it.SubItems.Add(img.Width + "×" + img.Height); it.Tag = f; list.Items.Add(it); } } catch { } } Renumber(); lblStatus.Text = "共 " + list.Items.Count + " 张待拼接"; } static bool IsImage(string f) { string ext = Path.GetExtension(f).ToLowerInvariant(); return ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp" || ext == ".gif" || ext == ".webp"; } void Renumber() { for (int i = 0; i < list.Items.Count; i++) list.Items[i].Text = (i + 1).ToString(); } void MoveItem(int delta) { if (list.SelectedItems.Count == 0) return; int i = list.SelectedItems[0].Index; int j = i + delta; if (j < 0 || j >= list.Items.Count) return; ListViewItem it = list.Items[i]; list.Items.RemoveAt(i); list.Items.Insert(j, it); it.Selected = true; Renumber(); } string AlignName() { string a = cmbAlign.SelectedIndex == 1 ? "center" : cmbAlign.SelectedIndex == 2 ? "right" : "left"; if (rbH.Checked) a = cmbAlign.SelectedIndex == 1 ? "middle" : cmbAlign.SelectedIndex == 2 ? "bottom" : "top"; return a; } void DoStitch() { if (list.Items.Count < 2) { lblStatus.Text = "至少要两张图片"; return; } List imgs = new List(); try { foreach (ListViewItem it in list.Items) imgs.Add(new Bitmap((string)it.Tag)); int target = chkTarget.Checked ? (int)numTarget.Value : 0; using (Bitmap canvas = StitchOps.Render(imgs, rbV.Checked ? "v" : "h", (int)numGap.Value, AlignName(), target)) { Bitmap outBmp = StitchOps.Flatten(canvas, btnColor.Text == "白色" ? "white" : btnColor.Text == "黑色" ? "black" : "transparent"); string file = StitchOps.NextName(StitchOps.DefaultOutDir()); outBmp.Save(file, ImageFormat.Png); outBmp.Dispose(); lblStatus.Text = "已保存 " + file + "(" + canvas.Width + "×" + canvas.Height + ")"; try { System.Diagnostics.Process.Start("explorer.exe", "/select,\"" + file + "\""); } catch { } } } catch (Exception ex) { lblStatus.Text = "失败:" + ex.Message; } finally { foreach (Bitmap b in imgs) b.Dispose(); } } } /* ───────────── 自测 ───────────── */ public static class StitchSelfTest { static int _pass, _fail; static List _lines = new List(); static void Check(string name, object got, object want) { bool ok = string.Equals(got == null ? "" : got.ToString(), want == null ? "" : want.ToString()); if (ok) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " got=" + got + " want=" + want); } } static Bitmap Solid(int w, int h, Color c) { Bitmap b = new Bitmap(w, h, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(b)) g.Clear(c); return b; } static Color Px(Bitmap b, int x, int y) { return b.GetPixel(x, y); } public static int Run(string dir) { _pass = 0; _fail = 0; _lines = new List(); _lines.Add("长图拼接 自测 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); string baseDir = string.IsNullOrEmpty(dir) ? Path.Combine(Path.GetTempPath(), "gt-stitch-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); try { Console.OutputEncoding = Encoding.UTF8; } catch { } // 1. 自然排序 List names = new List { "img10.png", "img2.png", "img1.png" }; StitchOps.NaturalSort(names); Check("自然排序", string.Join(",", names.ToArray()), "img1.png,img2.png,img10.png"); // 2. 纵向拼接:尺寸 + 顺序 + 间距 Bitmap a = Solid(100, 60, Color.Red); Bitmap b = Solid(120, 40, Color.Blue); List two = new List { a, b }; using (Bitmap v = StitchOps.Render(two, "v", 0, "left", 0)) { Check("纵向尺寸", v.Width + "x" + v.Height, "120x100"); Check("上=红", Px(v, 10, 10), Color.FromArgb(255, 255, 0, 0)); Check("下=蓝", Px(v, 10, 80), Color.FromArgb(255, 0, 0, 255)); } // 3. 间距 using (Bitmap v = StitchOps.Render(two, "v", 10, "left", 0)) { Check("间距计入高度", v.Height, 110); Check("间隙是透明底", Px(v, 10, 65), Color.FromArgb(0, 0, 0, 0)); Check("第二图起始正确", Px(v, 10, 75), Color.FromArgb(255, 0, 0, 255)); } // 4. 对齐:居中/居右 using (Bitmap v = StitchOps.Render(two, "v", 0, "center", 0)) Check("居中偏移", Px(v, 5, 10), Color.FromArgb(0, 0, 0, 0)); // 红图宽100,画布120 → 左边 10px 透明 using (Bitmap v = StitchOps.Render(two, "v", 0, "right", 0)) Check("居右偏移", Px(v, 10, 10), Color.FromArgb(0, 0, 0, 0)); // 红图右贴边,左侧 20px 透明 // 5. 统一宽度缩放 using (Bitmap v = StitchOps.Render(two, "v", 0, "left", 240)) { Check("统一宽 240", v.Width, 240); Check("红图等比高", v.Height, 240 * 60 / 100 + 240 * 40 / 120); } // 6. 横向拼接 using (Bitmap h = StitchOps.Render(two, "h", 0, "top", 0)) { Check("横向尺寸", h.Width + "x" + h.Height, "220x60"); Check("左=红", Px(h, 10, 10), Color.FromArgb(255, 255, 0, 0)); Check("右=蓝", Px(h, 150, 10), Color.FromArgb(255, 0, 0, 255)); } // 7. 统一高度 using (Bitmap h = StitchOps.Render(two, "h", 0, "top", 120)) { Check("统一高 120", h.Height, 120); Check("横宽=等比和", h.Width, 100 * 120 / 60 + 120 * 120 / 40); } // 8. 三张顺序 Bitmap c = Solid(50, 30, Color.Green); List three = new List { a, b, c }; using (Bitmap v = StitchOps.Render(three, "v", 0, "left", 0)) Check("三张顺序", Px(v, 10, 125), Color.FromArgb(255, 0, 128, 0)); // 9. Flatten 白底 using (Bitmap t = StitchOps.Render(two, "v", 6, "left", 0)) using (Bitmap f = StitchOps.Flatten((Bitmap)t.Clone(), "white")) Check("白底填充", Px(f, 10, 63), Color.FromArgb(255, 255, 255, 255)); // 10. 命名 string n1 = StitchOps.NextName(baseDir); Check("命名格式", Path.GetFileName(n1).StartsWith("长图-"), true); // 11. Form 层就绪 StitchForm form = new StitchForm(); Check("窗口控件就绪", form.Controls.Count > 0, true); _lines.Add("结果: " + _pass + " 通过, " + _fail + " 失败" + (_fail == 0 ? " ✓" : " ✗")); } catch (Exception ex) { _lines.Add("异常: " + ex.GetType().Name + ": " + ex.Message); _fail++; } string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-stitch.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static int Main(string[] args) { if (args.Length >= 1 && args[0] == "--selftest") return StitchSelfTest.Run(args.Length >= 2 ? args[1] : null); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new StitchForm()); return 0; } } }