// 批量裁剪切图 - 绿色工具箱 // 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.Text; using System.Windows.Forms; namespace GreenToolbox { public class SliceForm : 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 rbGrid, rbFixed, rbRegion; private GroupBox gGrid, gFixed, gRegion; private NumericUpDown numRows, numCols, numW, numH, numX, numY, numRW, numRH; private ComboBox cmbAnchor; private CheckBox chkResize, chkSub, chkKeepFormat; private Button btnRun, btnGapPreset; private ProgressBar progress; private Label lblStatus; private PictureBox pic; private BackgroundWorker worker; private Image previewSrc = null; public SliceForm() { 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(960, 700); this.MinimumSize = new Size(960, 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 g0 = new GroupBox(); g0.Text = "切法"; g0.Location = new Point(x, y); g0.Size = new Size(544, 56); g0.ForeColor = COL_GREEN; g0.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g0); rbGrid = new RadioButton(); rbGrid.Text = "等分成几块"; rbGrid.Location = new Point(14, 22); rbGrid.AutoSize = true; rbGrid.Checked = true; rbGrid.ForeColor = this.ForeColor; rbGrid.Font = this.Font; rbGrid.CheckedChanged += new EventHandler(ModeChange); g0.Controls.Add(rbGrid); rbFixed = new RadioButton(); rbFixed.Text = "裁成固定尺寸"; rbFixed.Location = new Point(150, 22); rbFixed.AutoSize = true; rbFixed.ForeColor = this.ForeColor; rbFixed.Font = this.Font; rbFixed.CheckedChanged += new EventHandler(ModeChange); g0.Controls.Add(rbFixed); rbRegion = new RadioButton(); rbRegion.Text = "裁同一块区域"; rbRegion.Location = new Point(300, 22); rbRegion.AutoSize = true; rbRegion.ForeColor = this.ForeColor; rbRegion.Font = this.Font; rbRegion.CheckedChanged += new EventHandler(ModeChange); g0.Controls.Add(rbRegion); y += 68; // ---------------- 等分 ---------------- gGrid = new GroupBox(); gGrid.Text = "等分(朋友圈九宫格、长图切块)"; gGrid.Location = new Point(x, y); gGrid.Size = new Size(544, 104); gGrid.ForeColor = COL_GREEN; gGrid.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(gGrid); Label lr = new Label(); lr.Text = "横着切"; lr.AutoSize = true; lr.ForeColor = COL_GRAY; lr.Location = new Point(14, 32); lr.Font = this.Font; gGrid.Controls.Add(lr); numCols = new NumericUpDown(); numCols.Location = new Point(70, 28); numCols.Size = new Size(56, 26); numCols.Minimum = 1; numCols.Maximum = 20; numCols.Value = 3; numCols.ValueChanged += new EventHandler(AnyChange); gGrid.Controls.Add(numCols); Label lr2 = new Label(); lr2.Text = "列 × 竖着切"; lr2.AutoSize = true; lr2.ForeColor = COL_GRAY; lr2.Location = new Point(134, 32); lr2.Font = this.Font; gGrid.Controls.Add(lr2); numRows = new NumericUpDown(); numRows.Location = new Point(238, 28); numRows.Size = new Size(56, 26); numRows.Minimum = 1; numRows.Maximum = 20; numRows.Value = 3; numRows.ValueChanged += new EventHandler(AnyChange); gGrid.Controls.Add(numRows); Label lr3 = new Label(); lr3.Text = "行"; lr3.AutoSize = true; lr3.ForeColor = COL_GRAY; lr3.Location = new Point(300, 32); lr3.Font = this.Font; gGrid.Controls.Add(lr3); btnGapPreset = Flat("九宫格 3×3", new Point(338, 26), new Size(104, 30), false); btnGapPreset.Click += new EventHandler(PresetClick); gGrid.Controls.Add(btnGapPreset); Label lg = new Label(); lg.Text = "1 列 3 行 = 竖着切三块,适合长图发微信;3×3 = 朋友圈九宫格"; lg.AutoSize = true; lg.ForeColor = COL_GRAY; lg.Font = this.Font; lg.Location = new Point(14, 68); gGrid.Controls.Add(lg); // ---------------- 固定尺寸 ---------------- gFixed = new GroupBox(); gFixed.Text = "固定尺寸(头像、封面、报名照)"; gFixed.Location = new Point(x, y); gFixed.Size = new Size(544, 104); gFixed.ForeColor = COL_GREEN; gFixed.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); gFixed.Visible = false; this.Controls.Add(gFixed); Label lw = new Label(); lw.Text = "宽"; lw.AutoSize = true; lw.ForeColor = COL_GRAY; lw.Location = new Point(14, 32); lw.Font = this.Font; gFixed.Controls.Add(lw); numW = new NumericUpDown(); numW.Location = new Point(40, 28); numW.Size = new Size(70, 26); numW.Minimum = 16; numW.Maximum = 8000; numW.Value = 600; numW.ValueChanged += new EventHandler(AnyChange); gFixed.Controls.Add(numW); Label lh = new Label(); lh.Text = "高"; lh.AutoSize = true; lh.ForeColor = COL_GRAY; lh.Location = new Point(120, 32); lh.Font = this.Font; gFixed.Controls.Add(lh); numH = new NumericUpDown(); numH.Location = new Point(146, 28); numH.Size = new Size(70, 26); numH.Minimum = 16; numH.Maximum = 8000; numH.Value = 600; numH.ValueChanged += new EventHandler(AnyChange); gFixed.Controls.Add(numH); Label la = new Label(); la.Text = "取哪块"; la.AutoSize = true; la.ForeColor = COL_GRAY; la.Location = new Point(234, 32); la.Font = this.Font; gFixed.Controls.Add(la); cmbAnchor = new ComboBox(); cmbAnchor.DropDownStyle = ComboBoxStyle.DropDownList; cmbAnchor.Location = new Point(286, 28); cmbAnchor.Size = new Size(110, 26); cmbAnchor.Items.AddRange(new object[] { "居中", "左上", "右上", "左下", "右下" }); cmbAnchor.SelectedIndex = 0; cmbAnchor.SelectedIndexChanged += new EventHandler(AnyChange); gFixed.Controls.Add(cmbAnchor); chkResize = new CheckBox(); chkResize.Text = "原图比目标小就放大到目标尺寸"; chkResize.Location = new Point(14, 68); chkResize.AutoSize = true; chkResize.Checked = true; chkResize.ForeColor = this.ForeColor; chkResize.Font = this.Font; gFixed.Controls.Add(chkResize); // ---------------- 同一区域 ---------------- gRegion = new GroupBox(); gRegion.Text = "同一块区域(同尺寸截图批量去边框、去角标)"; gRegion.Location = new Point(x, y); gRegion.Size = new Size(544, 104); gRegion.ForeColor = COL_GREEN; gRegion.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); gRegion.Visible = false; this.Controls.Add(gRegion); Label lx = new Label(); lx.Text = "左"; lx.AutoSize = true; lx.ForeColor = COL_GRAY; lx.Location = new Point(14, 32); lx.Font = this.Font; gRegion.Controls.Add(lx); numX = new NumericUpDown(); numX.Location = new Point(40, 28); numX.Size = new Size(64, 26); numX.Minimum = 0; numX.Maximum = 20000; numX.Value = 0; gRegion.Controls.Add(numX); Label ly = new Label(); ly.Text = "上"; ly.AutoSize = true; ly.ForeColor = COL_GRAY; ly.Location = new Point(112, 32); ly.Font = this.Font; gRegion.Controls.Add(ly); numY = new NumericUpDown(); numY.Location = new Point(138, 28); numY.Size = new Size(64, 26); numY.Minimum = 0; numY.Maximum = 20000; numY.Value = 0; gRegion.Controls.Add(numY); Label lrw = new Label(); lrw.Text = "宽"; lrw.AutoSize = true; lrw.ForeColor = COL_GRAY; lrw.Location = new Point(212, 32); lrw.Font = this.Font; gRegion.Controls.Add(lrw); numRW = new NumericUpDown(); numRW.Location = new Point(238, 28); numRW.Size = new Size(64, 26); numRW.Minimum = 4; numRW.Maximum = 20000; numRW.Value = 800; gRegion.Controls.Add(numRW); Label lrh = new Label(); lrh.Text = "高"; lrh.AutoSize = true; lrh.ForeColor = COL_GRAY; lrh.Location = new Point(312, 32); lrh.Font = this.Font; gRegion.Controls.Add(lrh); numRH = new NumericUpDown(); numRH.Location = new Point(338, 28); numRH.Size = new Size(64, 26); numRH.Minimum = 4; numRH.Maximum = 20000; numRH.Value = 600; gRegion.Controls.Add(numRH); Label lreg = new Label(); lreg.Text = "像素坐标;右边预览有绿框,改数字就能看到位置"; lreg.AutoSize = true; lreg.ForeColor = COL_GRAY; lreg.Font = this.Font; lreg.Location = new Point(14, 68); gRegion.Controls.Add(lreg); y += 116; // ---------------- 输出 ---------------- GroupBox g4 = new GroupBox(); g4.Text = "输出"; g4.Location = new Point(x, y); g4.Size = new Size(544, 66); g4.ForeColor = COL_GREEN; g4.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g4); chkSub = new CheckBox(); chkSub.Text = "包含子文件夹"; chkSub.Location = new Point(14, 26); chkSub.AutoSize = true; chkSub.ForeColor = this.ForeColor; chkSub.Font = this.Font; g4.Controls.Add(chkSub); chkKeepFormat = new CheckBox(); chkKeepFormat.Text = "保留 PNG(默认统一转 JPG,体积更小)"; chkKeepFormat.Location = new Point(148, 26); chkKeepFormat.AutoSize = true; chkKeepFormat.Checked = true; chkKeepFormat.ForeColor = this.ForeColor; chkKeepFormat.Font = this.Font; g4.Controls.Add(chkKeepFormat); y += 78; 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 g5 = new GroupBox(); g5.Text = "切法预览"; g5.Location = new Point(588, 14); g5.Size = new Size(356, 672); g5.ForeColor = COL_GREEN; g5.Font = new Font("Microsoft YaHei UI", 9.5f, FontStyle.Bold); this.Controls.Add(g5); pic = new PictureBox(); pic.Location = new Point(10, 24); pic.Size = new Size(334, 632); pic.BackColor = COL_PANEL; pic.SizeMode = PictureBoxSizeMode.Normal; pic.BorderStyle = BorderStyle.FixedSingle; g5.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 ModeChange(object sender, EventArgs e) { gGrid.Visible = rbGrid.Checked; gFixed.Visible = rbFixed.Checked; gRegion.Visible = rbRegion.Checked; Render(); } private void PresetClick(object sender, EventArgs e) { numCols.Value = 3; numRows.Value = 3; } private void AnyChange(object sender, EventArgs e) { Render(); } 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]); lblStatus.Text = "共 " + files.Count + " 张,预览:" + Path.GetFileName(files[0]) + "(" + previewSrc.Width + "×" + previewSrc.Height + ")"; Render(); } catch (Exception ex) { lblStatus.Text = "预览失败:" + ex.Message; } } private void Render() { 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); int dw = (int)(previewSrc.Width * s), dh = (int)(previewSrc.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(previewSrc, dx, dy, dw, dh); } using (Graphics g = Graphics.FromImage(bmp)) { using (Pen p = new Pen(Color.FromArgb(220, 0, 145, 88), 1f)) using (Pen pw2 = new Pen(Color.FromArgb(160, 255, 255, 255), 3f)) { if (rbGrid.Checked) { int nc = (int)numCols.Value, nr = (int)numRows.Value; for (int c = 1; c < nc; c++) { int xx = dx + dw * c / nc; g.DrawLine(pw2, xx, dy, xx, dy + dh); g.DrawLine(p, xx, dy, xx, dy + dh); } for (int r = 1; r < nr; r++) { int yy = dy + dh * r / nr; g.DrawLine(pw2, dx, yy, dx + dw, yy); g.DrawLine(p, dx, yy, dx + dw, yy); } } else if (rbFixed.Checked) { int w = (int)numW.Value, h = (int)numH.Value; int cw = (int)Math.Round(w * s), ch = (int)Math.Round(h * s); int cx = dx + (dw - cw) / 2, cy = dy + (dh - ch) / 2; int ai = cmbAnchor.SelectedIndex; if (ai == 1) { cx = dx; cy = dy; } else if (ai == 2) { cx = dx + dw - cw; cy = dy; } else if (ai == 3) { cx = dx; cy = dy + dh - ch; } else if (ai == 4) { cx = dx + dw - cw; cy = dy + dh - ch; } g.DrawRectangle(pw2, cx, cy, cw, ch); g.DrawRectangle(p, cx, cy, cw, ch); } else { int rx = dx + (int)((int)numX.Value * s); int ry = dy + (int)((int)numY.Value * s); int rw = (int)((int)numRW.Value * s); int rh = (int)((int)numRH.Value * s); g.DrawRectangle(pw2, rx, ry, rw, rh); g.DrawRectangle(p, rx, ry, rw, rh); } } } Image old = pic.Image; pic.Image = bmp; if (old != null) old.Dispose(); } // ---------------------------------------------------------------- 批量 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 (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 { using (Image img = LoadPic(f)) { string stem = Path.GetFileNameWithoutExtension(f); if (rbGrid.Checked) SliceGrid(img, stem, outDir, jpeg, log); else if (rbFixed.Checked) SliceFixed(img, stem, outDir, jpeg, log); else SliceRegion(img, stem, outDir, jpeg, log); } ok++; } 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 string OutExt(string srcPath) { if (chkKeepFormat.Checked && srcPath.ToLower().EndsWith(".png")) return ".png"; return ".jpg"; } private void SaveTile(Bitmap bmp, string path, ImageCodecInfo jpeg) { if (path.ToLower().EndsWith(".png")) bmp.Save(path, ImageFormat.Png); else if (jpeg != null) bmp.Save(path, jpeg, Q(92)); else bmp.Save(path, ImageFormat.Jpeg); } private void SliceGrid(Image img, string stem, string outDir, ImageCodecInfo jpeg, StringBuilder log) { int nc = (int)numCols.Value, nr = (int)numRows.Value; int tw = img.Width / nc, th = img.Height / nr; if (tw < 1) tw = 1; if (th < 1) th = 1; string ext = OutExt("x.jpg"); // 每张切片另存,避免整图常驻内存 for (int r = 0; r < nr; r++) { for (int c = 0; c < nc; c++) { using (Bitmap tile = new Bitmap(tw, th, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(tile)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(img, new Rectangle(0, 0, tw, th), new Rectangle(c * tw, r * th, tw, th), GraphicsUnit.Pixel); } string name = stem + "_" + (r + 1) + "_" + (c + 1) + ext; SaveTile(tile, Path.Combine(outDir, name), jpeg); } } } log.AppendLine("OK " + stem + " -> " + (nc * nr) + " 块"); } private void SliceFixed(Image img, string stem, string outDir, ImageCodecInfo jpeg, StringBuilder log) { int w = (int)numW.Value, h = (int)numH.Value; int cw = Math.Min(w, img.Width), ch = Math.Min(h, img.Height); int cx, cy; int ai = cmbAnchor.SelectedIndex; if (ai == 1) { cx = 0; cy = 0; } else if (ai == 2) { cx = img.Width - cw; cy = 0; } else if (ai == 3) { cx = 0; cy = img.Height - ch; } else if (ai == 4) { cx = img.Width - cw; cy = img.Height - ch; } else { cx = (img.Width - cw) / 2; cy = (img.Height - ch) / 2; } using (Bitmap tile = new Bitmap(w, h, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(tile)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; // 先铺白底(放大时留白而不是黑边) g.Clear(Color.White); int dw = cw, dh = ch; if (chkResize.Checked && (img.Width < w || img.Height < h)) { double sc = Math.Max((double)w / cw, (double)h / ch); dw = (int)Math.Round(cw * sc); dh = (int)Math.Round(ch * sc); } g.DrawImage(img, new Rectangle((w - dw) / 2, (h - dh) / 2, dw, dh), new Rectangle(cx, cy, cw, ch), GraphicsUnit.Pixel); } SaveTile(tile, Path.Combine(outDir, stem + "_" + w + "x" + h + ".jpg"), jpeg); } log.AppendLine("OK " + stem + " -> " + w + "x" + h); } private void SliceRegion(Image img, string stem, string outDir, ImageCodecInfo jpeg, StringBuilder log) { int x = (int)numX.Value, y = (int)numY.Value; int w = (int)numRW.Value, h = (int)numRH.Value; if (x >= img.Width || y >= img.Height) { log.AppendLine("跳过 " + stem + "(图片比设定区域小)"); return; } w = Math.Min(w, img.Width - x); h = Math.Min(h, img.Height - y); using (Bitmap tile = new Bitmap(w, h, PixelFormat.Format24bppRgb)) { using (Graphics g = Graphics.FromImage(tile)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(img, new Rectangle(0, 0, w, h), new Rectangle(x, y, w, h), GraphicsUnit.Pixel); } SaveTile(tile, Path.Combine(outDir, stem + "_裁.jpg"), jpeg); } log.AppendLine("OK " + stem + " -> " + w + "x" + h); } 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 void LoadFolderForTest(string folder) { txtFolder.Text = folder; LoadPreview(); } public void SetGridForTest(int cols, int rows) { rbGrid.Checked = true; numCols.Value = cols; numRows.Value = rows; ModeChange(null, null); } 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 SetFixedForTest(int w, int h, int anchor) { rbFixed.Checked = true; numW.Value = w; numH.Value = h; cmbAnchor.SelectedIndex = anchor; ModeChange(null, null); } public void SetRegionForTest(int x, int y, int w, int h) { rbRegion.Checked = true; numX.Value = x; numY.Value = y; numRW.Value = w; numRH.Value = h; ModeChange(null, null); } } // 命令行自测:造四色块图 → 三种切法各跑一遍 → 断言块数、尺寸、每块颜色对不对 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()); } // Image.FromFile 会一直锁着文件,统一读进内存再解码 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)) return b.GetPixel(x, y); } private static string Near(Color got, Color want) { bool ok = Math.Abs(got.R - want.R) <= 16 && Math.Abs(got.G - want.G) <= 16 && Math.Abs(got.B - want.B) <= 16; return ok ? "是" : "是" + got.R + "," + got.G + "," + got.B; } // 每种切法一个独立文件夹,里面只放一张源图 private static string NewCase(string root, string name, string srcFile) { string d = Path.Combine(root, name); Directory.CreateDirectory(d); File.Copy(srcFile, Path.Combine(d, "grid.png"), true); return d; } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-slice-selftest"); try { if (Directory.Exists(dir)) { try { Directory.Delete(dir, true); } catch { } } Directory.CreateDirectory(dir); _lines.Add("批量裁剪切图 自测(" + dir + ")"); // 300x200:左上红、右上绿、左下蓝、右下黄,切完一眼能看出有没有错位 string src = Path.Combine(dir, "grid.png"); using (Bitmap b = new Bitmap(300, 200)) using (Graphics g = Graphics.FromImage(b)) { g.Clear(Color.Red); g.FillRectangle(Brushes.Lime, 150, 0, 150, 100); g.FillRectangle(Brushes.Blue, 0, 100, 150, 100); g.FillRectangle(Brushes.Yellow, 150, 100, 150, 100); b.Save(src, ImageFormat.Png); } SliceForm f = new SliceForm(); // 每种切法单独一个文件夹:产物就写在源图旁边,混在一起会让「处理几张」的断言失真 string c1 = NewCase(dir, "case1", src); string c2 = NewCase(dir, "case2", src); string c3 = NewCase(dir, "case3", src); // ① 等分:3 列 × 2 行 → 6 块,每块 100x100 f.LoadFolderForTest(c1); f.SetGridForTest(3, 2); object[] r1 = f.RunBatch(c1); CheckInt("等分:处理 1 张", (int)r1[1], 1); CheckInt("等分:失败 0 张", (int)r1[2], 0); string outDir = Path.Combine(c1, "切图"); CheckInt("等分:切出 6 块", Directory.GetFiles(outDir, "grid_*.jpg").Length, 6); using (Image t11 = Load(Path.Combine(outDir, "grid_1_1.jpg"))) using (Image t13 = Load(Path.Combine(outDir, "grid_1_3.jpg"))) using (Image t21 = Load(Path.Combine(outDir, "grid_2_1.jpg"))) using (Image t23 = Load(Path.Combine(outDir, "grid_2_3.jpg"))) { Check("等分:块尺寸 100x100", t11.Width + "x" + t11.Height, "100x100"); Check("等分:第 1 行 1 列是左上那块(红)", Near(Pixel(t11, 50, 50), Color.Red), "是"); Check("等分:第 1 行 3 列是右上那块(绿)", Near(Pixel(t13, 50, 50), Color.Lime), "是"); Check("等分:第 2 行 1 列是左下那块(蓝)", Near(Pixel(t21, 50, 50), Color.Blue), "是"); Check("等分:第 2 行 3 列是右下那块(黄)", Near(Pixel(t23, 50, 50), Color.Yellow), "是"); } f.RunBatch(c1); CheckInt("等分:再跑一次不会翻倍(同名直接覆盖)", Directory.GetFiles(Path.Combine(c1, "切图"), "*.jpg").Length, 6); // ② 固定尺寸 + 左上角锚点:160x120 的块应该正好是原图左上角 f.LoadFolderForTest(c2); f.SetFixedForTest(160, 120, 1); object[] r2 = f.RunBatch(c2); CheckInt("固定尺寸:处理 1 张", (int)r2[1], 1); string fixedPath = Path.Combine(c2, "切图", "grid_160x120.jpg"); Check("固定尺寸:文件名带尺寸", File.Exists(fixedPath) ? "在" : "不在", "在"); using (Image tf = Load(fixedPath)) { Check("固定尺寸:尺寸就是 160x120", tf.Width + "x" + tf.Height, "160x120"); Check("固定尺寸:左上锚点取到的是原图左上(红)", Near(Pixel(tf, 5, 5), Color.Red), "是"); // 源图 200 高、裁 120 高,所以 y=100 以下那 20 像素会带进下半张的蓝 —— 说明窗口确实是左上对齐的 Check("固定尺寸:窗口左上对齐(y=105 已经进到下半张的蓝)", Near(Pixel(tf, 5, 105), Color.Blue), "是"); } // ③ 固定区域:从 (150,100) 裁 120x80,整块落在黄色里 f.LoadFolderForTest(c3); f.SetRegionForTest(150, 100, 120, 80); object[] r3 = f.RunBatch(c3); CheckInt("固定区域:处理 1 张", (int)r3[1], 1); string regPath = Path.Combine(c3, "切图", "grid_裁.jpg"); Check("固定区域:产出 grid_裁.jpg", File.Exists(regPath) ? "在" : "不在", "在"); using (Image tr = Load(regPath)) { Check("固定区域:尺寸 120x80", tr.Width + "x" + tr.Height, "120x80"); Check("固定区域:取的是右下那块(黄)", Near(Pixel(tr, 60, 40), Color.Yellow), "是"); } // ④ 区域超出图片边界时自动收窄,不能崩 f.SetRegionForTest(250, 150, 200, 200); object[] r4 = f.RunBatch(c3); CheckInt("固定区域:超出边界不报失败", (int)r4[2], 0); using (Image tx = Load(regPath)) Check("固定区域:超出边界时收窄到 50x50", tx.Width + "x" + tx.Height, "50x50"); // ⑤ 空文件夹不炸 string empty = Path.Combine(dir, "空文件夹"); Directory.CreateDirectory(empty); f.LoadFolderForTest(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-slice.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); // 自测:SliceTool.exe --selftest [工作目录] (退出码 0 全过 / 1 有失败) if (args.Length >= 1 && args[0] == "--selftest") { Environment.Exit(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } // 临时驱动(截图/核对脚本用):--batch <图片文件夹> [列] [行] if (args.Length >= 2 && args[0] == "--batch") { int cols = args.Length >= 4 ? int.Parse(args[2]) : 3; int rows = args.Length >= 4 ? int.Parse(args[3]) : 3; SliceForm f = new SliceForm(); f.LoadFolderForTest(args[1]); f.SetGridForTest(cols, rows); object[] r = f.RunBatch(args[1]); Console.WriteLine("files=" + r[0] + " ok=" + r[1] + " fail=" + r[2] + " out=" + r[3]); return; } Application.Run(new SliceForm()); } } }