// 图片批量改尺寸 - 绿色工具箱 // 单文件零依赖,C# 5.0 语法 // 功能:按宽度/高度/长边/百分比/精确尺寸批量缩放,默认不放大、默认输出到子目录不动原图 // 边界:只处理常见位图(jpg/png/bmp/gif/tif);不做智能裁剪、不做超分 // 细节:手机照片按 EXIF 方向自动摆正;保留原 DPI,打印尺寸不变形 using System; using System.Collections.Generic; 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 ResizeSpec { public const int ModeWidth = 0; // 按宽度,高度等比 public const int ModeHeight = 1; // 按高度,宽度等比 public const int ModeLongEdge = 2; // 长边不超过 public const int ModePercent = 3; // 按百分比 public const int ModeExact = 4; // 精确宽高 public int Mode = ModeWidth; public int W = 1920; public int H = 1080; public int LongEdge = 1920; public int Percent = 50; public bool NoUpscale = true; public string OutExt = ""; // 空 = 保持原格式 public ResizeSpec Clone() { ResizeSpec s = new ResizeSpec(); s.Mode = Mode; s.W = W; s.H = H; s.LongEdge = LongEdge; s.Percent = Percent; s.NoUpscale = NoUpscale; s.OutExt = OutExt; return s; } } public static class ResizeOps { static readonly string[] Exts = new string[] { ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tif", ".tiff" }; public static bool IsImage(string path) { if (string.IsNullOrEmpty(path)) return false; string e = Path.GetExtension(path).ToLowerInvariant(); for (int i = 0; i < Exts.Length; i++) if (e == Exts[i]) return true; return false; } public static List CollectImages(string dir, bool sub) { List r = new List(); if (!Directory.Exists(dir)) return r; try { string[] files = Directory.GetFiles(dir, "*.*", sub ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); Array.Sort(files, StringComparer.CurrentCultureIgnoreCase); for (int i = 0; i < files.Length; i++) if (IsImage(files[i])) r.Add(files[i]); } catch { } return r; } public static int Clamp(int v, int min, int max) { if (v < min) return min; if (v > max) return max; return v; } // 纯函数:给定原尺寸和规则,算出目标尺寸。规则里所有异常输入都收敛到 1 像素起 public static Size Calc(int srcW, int srcH, ResizeSpec sp) { if (srcW <= 0 || srcH <= 0) return new Size(1, 1); int w = srcW, h = srcH; if (sp.Mode == ResizeSpec.ModeWidth) { int tw = Clamp(sp.W, 1, 20000); if (sp.NoUpscale && tw >= srcW) return new Size(srcW, srcH); h = (int)Math.Round((double)srcH * tw / srcW); w = tw; } else if (sp.Mode == ResizeSpec.ModeHeight) { int th = Clamp(sp.H, 1, 20000); if (sp.NoUpscale && th >= srcH) return new Size(srcW, srcH); w = (int)Math.Round((double)srcW * th / srcH); h = th; } else if (sp.Mode == ResizeSpec.ModeLongEdge) { int edge = Clamp(sp.LongEdge, 1, 20000); int srcLong = Math.Max(srcW, srcH); if (srcLong <= edge) return new Size(srcW, srcH); double k = (double)edge / srcLong; w = Math.Max(1, (int)Math.Round(srcW * k)); h = Math.Max(1, (int)Math.Round(srcH * k)); } else if (sp.Mode == ResizeSpec.ModePercent) { int p = Clamp(sp.Percent, 1, 400); w = Math.Max(1, (int)Math.Round(srcW * p / 100.0)); h = Math.Max(1, (int)Math.Round(srcH * p / 100.0)); } else { w = Clamp(sp.W, 1, 20000); h = Clamp(sp.H, 1, 20000); } if (w < 1) w = 1; if (h < 1) h = 1; return new Size(w, h); } public static int ReadOrientation(Image img) { try { PropertyItem[] items = img.PropertyItems; for (int i = 0; i < items.Length; i++) { if (items[i].Id == 0x0112 && items[i].Value != null && items[i].Value.Length >= 2) return BitConverter.ToInt16(items[i].Value, 0); } } catch { } return 1; } // 6/8 是竖拍,宽高要先对调再算 public static bool SwapForOrientation(int orientation) { return orientation >= 5 && orientation <= 8; } static void ApplyOrientation(Bitmap bmp, int orientation) { if (orientation == 3) bmp.RotateFlip(RotateFlipType.Rotate180FlipNone); else if (orientation == 6) bmp.RotateFlip(RotateFlipType.Rotate90FlipNone); else if (orientation == 8) bmp.RotateFlip(RotateFlipType.Rotate270FlipNone); } public static Bitmap LoadAndOrient(string src, out int srcW, out int srcH) { using (Image img = Image.FromFile(src)) { int orient = ReadOrientation(img); srcW = img.Width; srcH = img.Height; Bitmap full = new Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb); full.SetResolution(img.HorizontalResolution > 0 ? img.HorizontalResolution : 96f, img.VerticalResolution > 0 ? img.VerticalResolution : 96f); using (Graphics g = Graphics.FromImage(full)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height)); } ApplyOrientation(full, orient); if (SwapForOrientation(orient)) { srcW = img.Height; srcH = img.Width; } return full; } } // 返回写出的字节数;dst 已存在时由调用方保证不覆盖 public static long Process(string src, string dst, ResizeSpec sp) { int sw, sh; using (Bitmap full = LoadAndOrient(src, out sw, out sh)) { Size target = Calc(sw, sh, sp); using (Bitmap dstBmp = new Bitmap(target.Width, target.Height, PixelFormat.Format24bppRgb)) { float dpi = full.HorizontalResolution > 0 ? full.HorizontalResolution : 96f; dstBmp.SetResolution(dpi, full.VerticalResolution > 0 ? full.VerticalResolution : dpi); using (Graphics g = Graphics.FromImage(dstBmp)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.DrawImage(full, new Rectangle(0, 0, target.Width, target.Height)); } string ext = Path.GetExtension(dst).ToLowerInvariant(); Directory.CreateDirectory(Path.GetDirectoryName(dst)); if (ext == ".jpg" || ext == ".jpeg") { ImageCodecInfo jpg = FindEncoder("image/jpeg"); if (jpg != null) { using (EncoderParameters ps = new EncoderParameters(1)) { ps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 92L); dstBmp.Save(dst, jpg, ps); } } else dstBmp.Save(dst, ImageFormat.Jpeg); } else if (ext == ".png") dstBmp.Save(dst, ImageFormat.Png); else if (ext == ".gif") dstBmp.Save(dst, ImageFormat.Gif); else if (ext == ".tif" || ext == ".tiff") dstBmp.Save(dst, ImageFormat.Tiff); else dstBmp.Save(dst, ImageFormat.Bmp); return new FileInfo(dst).Length; } } } static ImageCodecInfo FindEncoder(string mime) { ImageCodecInfo[] all = ImageCodecInfo.GetImageEncoders(); for (int i = 0; i < all.Length; i++) if (string.Equals(all[i].MimeType, mime, StringComparison.OrdinalIgnoreCase)) return all[i]; return null; } // 目标格式:spec.OutExt 为空则跟随源文件(jpg 统一成 .jpg,避免 .jpeg 两套) public static string TargetExt(string src, ResizeSpec sp) { if (!string.IsNullOrEmpty(sp.OutExt)) return sp.OutExt; string e = Path.GetExtension(src).ToLowerInvariant(); if (e == ".jpeg") return ".jpg"; if (e == ".tif") return ".tif"; return e; } public static string OutName(string src, ResizeSpec sp, string outDir, string suffix) { string name = Path.GetFileNameWithoutExtension(src); string ext = TargetExt(src, sp); if (suffix == null) suffix = ""; string baseName = name + suffix; string full = Path.Combine(outDir, baseName + ext); int i = 2; while (File.Exists(full)) { full = Path.Combine(outDir, baseName + "(" + i + ")" + ext); i++; } return full; } public static string SizeText(int w, int h) { return w + " × " + h; } public static string DefaultSuffix(ResizeSpec sp) { if (sp.Mode == ResizeSpec.ModeWidth) return "_w" + sp.W; if (sp.Mode == ResizeSpec.ModeHeight) return "_h" + sp.H; if (sp.Mode == ResizeSpec.ModeLongEdge) return "_long" + sp.LongEdge; if (sp.Mode == ResizeSpec.ModePercent) return "_" + sp.Percent + "pct"; return "_" + sp.W + "x" + sp.H; } } public class ImgResizeForm : Form { List _files = new List(); ListView _list; ComboBox _mode; NumericUpDown _num1, _num2, _num3; Label _lb1, _lb2; CheckBox _noUp; ComboBox _fmt; TextBox _outDir, _suffix; Button _start; ProgressBar _bar; Label _status; Timer _work; int _cursor; int _ok, _fail; ResizeSpec _spec; string _curOut; string _curSuffix; public ImgResizeForm() { Text = "图片批量改尺寸 - 绿色工具箱"; ClientSize = new Size(900, 640); MinimumSize = new Size(760, 560); StartPosition = FormStartPosition.CenterScreen; Font = new Font("Microsoft YaHei UI", 9F); Panel top = new Panel(); top.Dock = DockStyle.Top; top.Height = 112; top.Padding = new Padding(12, 10, 12, 8); Label lbMode = new Label(); lbMode.Text = "缩放方式"; lbMode.SetBounds(12, 16, 60, 22); top.Controls.Add(lbMode); _mode = new ComboBox(); _mode.DropDownStyle = ComboBoxStyle.DropDownList; _mode.Items.AddRange(new object[] { "按宽度(高度自动等比)", "按高度(宽度自动等比)", "限制长边不超过", "按百分比缩放", "精确宽高(可能变形)" }); _mode.SelectedIndex = 0; _mode.SetBounds(76, 12, 210, 26); _mode.SelectedIndexChanged += delegate { SyncMode(); }; top.Controls.Add(_mode); _lb1 = new Label(); _lb1.SetBounds(300, 16, 40, 22); _lb1.Text = "宽度"; top.Controls.Add(_lb1); _num1 = new NumericUpDown(); _num1.Minimum = 1; _num1.Maximum = 20000; _num1.Value = 1920; _num1.SetBounds(342, 12, 82, 26); top.Controls.Add(_num1); _lb2 = new Label(); _lb2.SetBounds(434, 16, 46, 22); _lb2.Text = "像素"; top.Controls.Add(_lb2); _num2 = new NumericUpDown(); _num2.Minimum = 1; _num2.Maximum = 20000; _num2.Value = 1080; _num2.SetBounds(478, 12, 82, 26); top.Controls.Add(_num2); _num3 = new NumericUpDown(); _num3.Minimum = 1; _num3.Maximum = 400; _num3.Value = 50; _num3.SetBounds(342, 12, 82, 26); _num3.Visible = false; top.Controls.Add(_num3); _noUp = new CheckBox(); _noUp.Text = "小图不放大(推荐)"; _noUp.Checked = true; _noUp.SetBounds(578, 15, 160, 22); top.Controls.Add(_noUp); Label lbFmt = new Label(); lbFmt.Text = "输出格式"; lbFmt.SetBounds(12, 52, 60, 22); top.Controls.Add(lbFmt); _fmt = new ComboBox(); _fmt.DropDownStyle = ComboBoxStyle.DropDownList; _fmt.Items.AddRange(new object[] { "保持原格式", "统一 JPG", "统一 PNG", "统一 BMP" }); _fmt.SelectedIndex = 0; _fmt.SetBounds(76, 48, 130, 26); top.Controls.Add(_fmt); Label lbOut = new Label(); lbOut.Text = "输出到"; lbOut.SetBounds(224, 52, 50, 22); top.Controls.Add(lbOut); _outDir = new TextBox(); _outDir.SetBounds(274, 48, 400, 26); _outDir.Text = ""; top.Controls.Add(_outDir); Button browse = new Button(); browse.Text = "选择…"; browse.SetBounds(680, 47, 72, 28); browse.Click += delegate { FolderBrowserDialog d = new FolderBrowserDialog(); if (d.ShowDialog() == DialogResult.OK) _outDir.Text = d.SelectedPath; }; top.Controls.Add(browse); Label lbSuffix = new Label(); lbSuffix.Text = "文件名后缀"; lbSuffix.SetBounds(12, 84, 74, 22); top.Controls.Add(lbSuffix); _suffix = new TextBox(); _suffix.SetBounds(90, 80, 140, 26); _suffix.Text = "_w1920"; top.Controls.Add(_suffix); Label note = new Label(); note.Text = "留空则不加后缀;输出目录为空时自动在原图旁建「改尺寸」子文件夹,原图永不覆盖"; note.AutoSize = false; note.SetBounds(244, 84, 620, 20); note.ForeColor = Color.FromArgb(140, 145, 150); top.Controls.Add(note); Controls.Add(top); Panel ops = new Panel(); ops.Dock = DockStyle.Top; ops.Height = 42; ops.Padding = new Padding(12, 4, 12, 4); Button addFiles = new Button(); addFiles.Text = "添加图片"; addFiles.SetBounds(12, 6, 88, 30); addFiles.Click += delegate { AddFiles(); }; ops.Controls.Add(addFiles); Button addDir = new Button(); addDir.Text = "添加文件夹"; addDir.SetBounds(106, 6, 100, 30); addDir.Click += delegate { AddFolder(); }; ops.Controls.Add(addDir); Button clear = new Button(); clear.Text = "清空列表"; clear.SetBounds(212, 6, 88, 30); clear.Click += delegate { if (_cursor > 0) return; _files.Clear(); Reload(); _status.Text = "列表已清空"; }; ops.Controls.Add(clear); _start = new Button(); _start.Text = "开始处理"; _start.SetBounds(680, 6, 100, 30); _start.BackColor = Color.FromArgb(46, 160, 92); _start.ForeColor = Color.White; _start.FlatStyle = FlatStyle.Flat; _start.Click += delegate { StartWork(); }; ops.Controls.Add(_start); Button openOut = new Button(); openOut.Text = "打开输出目录"; openOut.SetBounds(786, 6, 104, 30); openOut.Click += delegate { string d = _outDir.Text.Trim(); if (d.Length == 0 && _files.Count > 0) d = Path.Combine(Path.GetDirectoryName(_files[0]), "改尺寸"); if (Directory.Exists(d)) { try { System.Diagnostics.Process.Start("explorer.exe", d); } catch { } } else _status.Text = "输出目录还不存在,先处理一批吧"; }; ops.Controls.Add(openOut); Controls.Add(ops); _list = new ListView(); _list.Dock = DockStyle.Fill; _list.View = View.Details; _list.FullRowSelect = true; _list.GridLines = true; _list.Columns.Add("文件", 380); _list.Columns.Add("原尺寸", 110); _list.Columns.Add("输出尺寸", 120); _list.Columns.Add("状态", 220); Controls.Add(_list); Panel bottom = new Panel(); bottom.Dock = DockStyle.Bottom; bottom.Height = 52; _bar = new ProgressBar(); _bar.Dock = DockStyle.Top; _bar.Height = 10; _bar.Style = ProgressBarStyle.Continuous; bottom.Controls.Add(_bar); _status = new Label(); _status.Dock = DockStyle.Fill; _status.TextAlign = ContentAlignment.MiddleLeft; _status.Padding = new Padding(12, 0, 0, 0); _status.ForeColor = Color.FromArgb(100, 105, 110); _status.Text = "支持 jpg / png / bmp / gif / tif,可一次拖入多张"; bottom.Controls.Add(_status); Controls.Add(bottom); AllowDrop = true; DragEnter += delegate(object s, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; }; DragDrop += delegate(object s, DragEventArgs e) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop); AddPaths(paths, true); }; // 停靠布局按 z-order 逆序计算:主列表最先布局,否则顶部设置区盖住列表 Controls.SetChildIndex(_list, 0); Controls.SetChildIndex(bottom, 1); Controls.SetChildIndex(ops, 2); Controls.SetChildIndex(top, 3); _work = new Timer(); _work.Interval = 40; _work.Tick += delegate { StepWork(); }; SyncMode(); } void SyncMode() { int i = _mode.SelectedIndex; bool w = i == 0 || i == 4; bool h = i == 1 || i == 4; bool edge = i == 2; bool pct = i == 3; _lb1.Visible = w || pct; _num1.Visible = w || pct; _lb1.Text = pct ? "百分比" : "宽度"; _lb2.Visible = h; _num2.Visible = h; _num3.Visible = edge; _noUp.Visible = i != 4; if (edge) { _lb1.Visible = true; _lb1.Text = "长边"; _num1.Visible = false; } if (pct) { _lb2.Text = "%"; } ResizeSpec sp = BuildSpec(); if (sp != null && _suffix.Text.Length > 0 && _suffix.Text.StartsWith("_")) _suffix.Text = ResizeOps.DefaultSuffix(sp); Reload(); } ResizeSpec BuildSpec() { ResizeSpec sp = new ResizeSpec(); sp.Mode = _mode.SelectedIndex; sp.W = (int)_num1.Value; sp.H = (int)_num2.Value; sp.LongEdge = (int)_num3.Value; sp.Percent = (int)_num3.Value; sp.NoUpscale = _noUp.Checked; if (_fmt.SelectedIndex == 1) sp.OutExt = ".jpg"; else if (_fmt.SelectedIndex == 2) sp.OutExt = ".png"; else if (_fmt.SelectedIndex == 3) sp.OutExt = ".bmp"; return sp; } void AddFiles() { OpenFileDialog d = new OpenFileDialog(); d.Multiselect = true; d.Filter = "图片|*.jpg;*.jpeg;*.png;*.bmp;*.gif;*.tif;*.tiff|所有文件|*.*"; if (d.ShowDialog() != DialogResult.OK) return; AddPaths(d.FileNames, true); } void AddFolder() { FolderBrowserDialog d = new FolderBrowserDialog(); if (d.ShowDialog() != DialogResult.OK) return; List got = ResizeOps.CollectImages(d.SelectedPath, true); AddPaths(got.ToArray(), false); } void AddPaths(string[] paths, bool filterImage) { if (paths == null) return; int added = 0; for (int i = 0; i < paths.Length; i++) { string p = paths[i]; if (Directory.Exists(p)) { List inner = ResizeOps.CollectImages(p, true); for (int k = 0; k < inner.Count; k++) if (!_files.Contains(inner[k])) { _files.Add(inner[k]); added++; } continue; } if (filterImage && !ResizeOps.IsImage(p)) continue; if (!File.Exists(p)) continue; if (_files.Contains(p)) continue; _files.Add(p); added++; } Reload(); _status.Text = "新增 " + added + " 张,共 " + _files.Count + " 张"; } void Reload() { ResizeSpec sp = BuildSpec(); _list.BeginUpdate(); _list.Items.Clear(); for (int i = 0; i < _files.Count; i++) { string f = _files[i]; ListViewItem it = new ListViewItem(f); string sizeText = "—"; string outText = "—"; try { using (Image img = Image.FromFile(f)) { sizeText = ResizeOps.SizeText(img.Width, img.Height); int orient = ResizeOps.ReadOrientation(img); int sw = img.Width, sh = img.Height; if (ResizeOps.SwapForOrientation(orient)) { sw = img.Height; sh = img.Width; } Size t = ResizeOps.Calc(sw, sh, sp); outText = ResizeOps.SizeText(t.Width, t.Height); } } catch { outText = "读不了"; } it.SubItems.Add(sizeText); it.SubItems.Add(outText); it.SubItems.Add(""); it.Tag = f; _list.Items.Add(it); } _list.EndUpdate(); _bar.Maximum = Math.Max(1, _files.Count); _bar.Value = 0; } void StartWork() { if (_work.Enabled) return; if (_files.Count == 0) { MessageBox.Show("先添加几张图片吧。", "提示"); return; } _spec = BuildSpec(); _curSuffix = _suffix.Text.Trim(); _curOut = _outDir.Text.Trim(); _cursor = 0; _ok = 0; _fail = 0; _bar.Maximum = _files.Count; _bar.Value = 0; _start.Enabled = false; for (int i = 0; i < _list.Items.Count; i++) _list.Items[i].SubItems[3].Text = "等待"; _status.Text = "开始处理…"; _work.Start(); } void StepWork() { if (_cursor >= _files.Count) { _work.Stop(); _start.Enabled = true; _status.Text = "完成:成功 " + _ok + " 张,失败 " + _fail + " 张"; return; } string src = _files[_cursor]; ListViewItem row = _list.Items[_cursor]; try { string outDir = _curOut; if (outDir.Length == 0) outDir = Path.Combine(Path.GetDirectoryName(src), "改尺寸"); Directory.CreateDirectory(outDir); string dst = ResizeOps.OutName(src, _spec, outDir, _curSuffix); long bytes = ResizeOps.Process(src, dst, _spec); row.SubItems[3].Text = "完成 " + (bytes / 1024) + " KB"; row.ForeColor = Color.FromArgb(0, 120, 60); _ok++; } catch (Exception ex) { row.SubItems[3].Text = "失败:" + ex.Message; row.ForeColor = Color.FromArgb(190, 60, 60); _fail++; } _cursor++; _bar.Value = Math.Min(_bar.Maximum, _cursor); _status.Text = "处理中 " + _cursor + " / " + _files.Count + "…"; } } public static class ResizeSelfTest { 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 string MakeImage(string dir, string name, int w, int h, Color c) { string p = Path.Combine(dir, name); using (Bitmap b = new Bitmap(w, h)) { using (Graphics g = Graphics.FromImage(b)) { g.Clear(c); using (SolidBrush br = new SolidBrush(Color.White)) g.FillRectangle(br, 0, 0, w / 4, h / 4); } b.Save(p, ImageFormat.Png); } return p; } 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-resize-" + Guid.NewGuid().ToString("N").Substring(0, 8)) : dir; try { Directory.CreateDirectory(baseDir); // 格式识别 Check("识别 jpg", ResizeOps.IsImage("a.JPG"), true); Check("识别 png", ResizeOps.IsImage(@"C:\x\b.png"), true); Check("识别 tif", ResizeOps.IsImage("c.tiff"), true); Check("txt 不算图片", ResizeOps.IsImage("d.txt"), false); Check("空路径不算", ResizeOps.IsImage(""), false); // 尺寸计算:按宽 ResizeSpec sp = new ResizeSpec(); sp.Mode = ResizeSpec.ModeWidth; sp.W = 800; Size s1 = ResizeOps.Calc(1600, 1200, sp); Check("按宽等比缩小", ResizeOps.SizeText(s1.Width, s1.Height), "800 × 600"); Check("按宽不放大(小图)", ResizeOps.SizeText( ResizeOps.Calc(400, 300, sp).Width, ResizeOps.Calc(400, 300, sp).Height), "400 × 300"); sp.NoUpscale = false; Check("允许放大时按规则放大", ResizeOps.SizeText( ResizeOps.Calc(400, 300, sp).Width, ResizeOps.Calc(400, 300, sp).Height), "800 × 600"); sp.NoUpscale = true; // 按高 sp.Mode = ResizeSpec.ModeHeight; sp.H = 600; Size s2 = ResizeOps.Calc(1920, 1080, sp); Check("按高等比缩小", ResizeOps.SizeText(s2.Width, s2.Height), "1067 × 600"); // 长边 sp.Mode = ResizeSpec.ModeLongEdge; sp.LongEdge = 1000; Size s3 = ResizeOps.Calc(4000, 3000, sp); Check("横图长边压到 1000", ResizeOps.SizeText(s3.Width, s3.Height), "1000 × 750"); Size s4 = ResizeOps.Calc(3000, 4000, sp); Check("竖图按高压缩", ResizeOps.SizeText(s4.Width, s4.Height), "750 × 1000"); Check("长边已达标不动", ResizeOps.SizeText( ResizeOps.Calc(800, 600, sp).Width, ResizeOps.Calc(800, 600, sp).Height), "800 × 600"); // 百分比 sp.Mode = ResizeSpec.ModePercent; sp.Percent = 50; Size s5 = ResizeOps.Calc(1200, 900, sp); Check("缩小一半", ResizeOps.SizeText(s5.Width, s5.Height), "600 × 450"); sp.Percent = 150; Size s6 = ResizeOps.Calc(1200, 900, sp); Check("放大到 150%", ResizeOps.SizeText(s6.Width, s6.Height), "1800 × 1350"); // 精确 sp.Mode = ResizeSpec.ModeExact; sp.W = 640; sp.H = 640; Size s7 = ResizeOps.Calc(1920, 1080, sp); Check("精确尺寸强制拉伸", ResizeOps.SizeText(s7.Width, s7.Height), "640 × 640"); // 异常输入收敛 sp.Mode = ResizeSpec.ModeWidth; sp.W = 0; Check("宽度 0 收敛为 1", ResizeOps.Calc(100, 100, sp).Width, 1); Check("原图 0 宽返回 1", ResizeOps.Calc(0, 100, sp).Width, 1); // 后缀 ResizeSpec sp2 = new ResizeSpec(); sp2.Mode = ResizeSpec.ModeWidth; sp2.W = 1280; Check("按宽默认后缀", ResizeOps.DefaultSuffix(sp2), "_w1280"); sp2.Mode = ResizeSpec.ModePercent; sp2.Percent = 30; Check("百分比默认后缀", ResizeOps.DefaultSuffix(sp2), "_30pct"); sp2.Mode = ResizeSpec.ModeLongEdge; sp2.LongEdge = 800; Check("长边默认后缀", ResizeOps.DefaultSuffix(sp2), "_long800"); sp2.Mode = ResizeSpec.ModeExact; sp2.W = 100; sp2.H = 200; Check("精确尺寸默认后缀", ResizeOps.DefaultSuffix(sp2), "_100x200"); // 输出命名 string big = MakeImage(baseDir, "大图.png", 2000, 1500, Color.SeaGreen); ResizeSpec sp3 = new ResizeSpec(); sp3.Mode = ResizeSpec.ModeWidth; sp3.W = 800; string outDir = Path.Combine(baseDir, "out"); Check("跟随源格式", ResizeOps.TargetExt("x.jpeg", sp3), ".jpg"); Check("输出文件名带后缀", Path.GetFileName( ResizeOps.OutName(big, sp3, outDir, "_w800")), "大图_w800.png"); Directory.CreateDirectory(outDir); File.WriteAllText(Path.Combine(outDir, "大图_w800.png"), "占位"); Check("重名自动加序号", Path.GetFileName( ResizeOps.OutName(big, sp3, outDir, "_w800")), "大图_w800(2).png"); ResizeSpec sp4 = sp3.Clone(); sp4.OutExt = ".jpg"; Check("强制格式改扩展名", Path.GetFileName( ResizeOps.OutName(big, sp4, outDir, "_w800")), "大图_w800.jpg"); // 真处理:2000×1500 → 宽 800 string dst1 = Path.Combine(outDir, "真处理.png"); long bytes = ResizeOps.Process(big, dst1, sp3); Check("输出文件存在", File.Exists(dst1), true); Check("输出体积大于 0", bytes > 0, true); using (Image o = Image.FromFile(dst1)) { Check("真处理输出宽度", o.Width, 800); Check("真处理输出高度(等比)", o.Height, 600); Check("输出仍是 PNG", o.RawFormat.Guid, ImageFormat.Png.Guid); } // 不放大:小图设 5000 宽,输出应保持原样 string small = MakeImage(baseDir, "小图.png", 320, 240, Color.Orange); ResizeSpec sp5 = new ResizeSpec(); sp5.Mode = ResizeSpec.ModeWidth; sp5.W = 5000; string dst2 = Path.Combine(outDir, "小图不动.png"); ResizeOps.Process(small, dst2, sp5); using (Image o = Image.FromFile(dst2)) { Check("小图没被放大", o.Width + "x" + o.Height, "320x240"); } // JPEG 输出 string jpgIn = Path.Combine(baseDir, "源.jpg"); using (Bitmap b = new Bitmap(1200, 800)) { using (Graphics g = Graphics.FromImage(b)) g.Clear(Color.SteelBlue); b.Save(jpgIn, ImageFormat.Jpeg); } ResizeSpec sp6 = new ResizeSpec(); sp6.Mode = ResizeSpec.ModePercent; sp6.Percent = 25; sp6.OutExt = ".jpg"; string dst3 = Path.Combine(outDir, "源_out.jpg"); ResizeOps.Process(jpgIn, dst3, sp6); using (Image o = Image.FromFile(dst3)) { Check("JPEG 缩到四分之一宽", o.Width, 300); Check("JPEG 缩到四分之一高", o.Height, 200); Check("JPEG 格式正确", o.RawFormat.Guid, ImageFormat.Jpeg.Guid); } // 目录收集 Directory.CreateDirectory(Path.Combine(baseDir, "子目录")); MakeImage(Path.Combine(baseDir, "子目录"), "c.png", 10, 10, Color.Red); File.WriteAllText(Path.Combine(baseDir, "说明.txt"), "x"); List found = ResizeOps.CollectImages(baseDir, true); Check("收集含子目录图片", found.Count >= 4, true); Check("收集不含 txt", found.Contains(Path.Combine(baseDir, "说明.txt")), false); Check("不递归时只收顶层 3 张", ResizeOps.CollectImages(baseDir, false).Count, 3); // 尺寸文案 Check("尺寸文案", ResizeOps.SizeText(1920, 1080), "1920 × 1080"); } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { Directory.Delete(baseDir, true); } catch { } } _lines.Add(""); _lines.Add(_fail == 0 ? "结果:共 " + (_pass + _fail) + " 项,全部通过 ✓" : "结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-imgresize.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(ResizeSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ImgResizeForm()); } } }