// 轻量看图 - 绿色工具箱 // C# 5.0 语法,零依赖(只用 System.Drawing)。看 jpg/png/bmp/gif/tiff/ico // 定位:替掉又慢又带广告的系统「照片」应用,双击就开、滚轮缩放、左右翻页 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Windows.Forms; namespace GreenToolbox { // ===== 纯函数区(可自测,不碰界面) ===== public static class ViewOps { // GDI+ 认的格式。webp/avif 不认,要在页面上说明,别让用户白下载 public static readonly string[] EXT = new string[] { ".jpg", ".jpeg", ".jfif", ".png", ".bmp", ".gif", ".tif", ".tiff", ".ico" }; public static bool IsSupported(string path) { if (string.IsNullOrEmpty(path)) return false; string e = Path.GetExtension(path); if (string.IsNullOrEmpty(e)) return false; e = e.ToLowerInvariant(); for (int i = 0; i < EXT.Length; i++) { if (EXT[i] == e) return true; } return false; } // 文件大小:B 不带小数,KB 一位,MB/GB 两位。用 InvariantCulture, // 免得在德语/法语系统上出现 "1,24 MB" 这种逗号小数点 public static string FormatSize(long bytes) { if (bytes < 0) return "?"; if (bytes < 1024) return bytes.ToString(CultureInfo.InvariantCulture) + " B"; double kb = bytes / 1024.0; if (kb < 1024) return string.Format(CultureInfo.InvariantCulture, "{0:0.0} KB", kb); double mb = kb / 1024.0; if (mb < 1024) return string.Format(CultureInfo.InvariantCulture, "{0:0.00} MB", mb); return string.Format(CultureInfo.InvariantCulture, "{0:0.00} GB", mb / 1024.0); } public static string ZoomText(double zoom) { int p = (int)Math.Round(zoom * 100); return p.ToString(CultureInfo.InvariantCulture) + "%"; } // 缩得太小看不见、放得太大变马赛克,两头都掐死 public static double ClampZoom(double z) { if (z < 0.05) return 0.05; if (z > 8.0) return 8.0; return z; } // 适应窗口:只在需要缩小时缩,小图不放大(放大就糊,想要大自己滚轮) public static double FitZoom(int imgW, int imgH, int viewW, int viewH, int pad) { if (imgW <= 0 || imgH <= 0) return 1.0; double aw = viewW - pad * 2; double ah = viewH - pad * 2; if (aw < 16) aw = 16; if (ah < 16) ah = 16; double s = Math.Min(aw / imgW, ah / imgH); if (s > 1.0) s = 1.0; if (s < 0.01) s = 0.01; return s; } // 翻页:到头了绕回另一头。count 为 0 时返回 -1,别让调用方拿 -1 当索引 public static int Step(int cur, int count, int delta) { if (count <= 0) return -1; int n = (cur + delta) % count; if (n < 0) n += count; return n; } // 自然排序:"图2" 排在 "图10" 前面(纯字符串比较会把 10 排前面,用户会觉得乱) public static int NaturalCompare(string a, string b) { if (a == null) a = ""; if (b == null) b = ""; int i = 0, j = 0; while (i < a.Length && j < b.Length) { if (char.IsDigit(a[i]) && char.IsDigit(b[j])) { int si = i, sj = j; while (i < a.Length && char.IsDigit(a[i])) i++; while (j < b.Length && char.IsDigit(b[j])) j++; string na = a.Substring(si, i - si).TrimStart('0'); string nb = b.Substring(sj, j - sj).TrimStart('0'); if (na.Length != nb.Length) return na.Length - nb.Length; int c = string.CompareOrdinal(na, nb); if (c != 0) return c; } else { char ca = char.ToLowerInvariant(a[i]); char cb = char.ToLowerInvariant(b[j]); if (ca != cb) return ca < cb ? -1 : 1; i++; j++; } } return (a.Length - i) - (b.Length - j); } public static string InfoText(string file, int w, int h, long bytes, double zoom, int idx, int count) { string name = file == null ? "" : Path.GetFileName(file); string s = name + " · " + w + " × " + h; if (bytes > 0) s += " · " + FormatSize(bytes); s += " · " + ZoomText(zoom); if (count > 1 && idx >= 0) s += " · " + (idx + 1) + "/" + count; return s; } // 目录里的图片清单:只看支持的扩展名,按自然顺序排,翻页才不会乱跳 public static List ListImages(string dir) { List list = new List(); if (dir == null || !Directory.Exists(dir)) return list; string[] files; try { files = Directory.GetFiles(dir); } catch { return list; } for (int i = 0; i < files.Length; i++) { if (IsSupported(files[i])) list.Add(files[i]); } list.Sort(delegate(string x, string y) { return NaturalCompare(x, y); }); return list; } } public class ImageViewerForm : Form { private static readonly Color COL_BG = Color.FromArgb(30, 31, 34); private static readonly Color COL_BAR = Color.FromArgb(38, 40, 44); private static readonly Color COL_FG = Color.FromArgb(228, 230, 232); private static readonly Color COL_DIM = Color.FromArgb(150, 156, 160); private static readonly Color COL_GREEN = Color.FromArgb(0, 175, 105); private CanvasPanel canvas; private Panel bar; private Label status; private Timer slideTimer; private Bitmap _img; private string _path; private List _files = new List(); private int _idx = -1; private double _zoom = 1.0; private bool _fit = true; private float _ox, _oy; private int _rot; // 0/90/180/270 private bool _dragging; private Point _dragStart; private float _dragOx, _dragOy; private bool _fullscreen; private FormBorderStyle _oldBorder; private FormWindowState _oldState; private Rectangle _oldBounds; public ImageViewerForm() { InitUi(); slideTimer = new Timer(); slideTimer.Interval = 2500; slideTimer.Tick += new EventHandler(SlideTick); } private void InitUi() { this.Text = "轻量看图 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = COL_BG; this.ForeColor = COL_FG; this.ClientSize = new Size(980, 660); this.MinimumSize = new Size(560, 400); this.StartPosition = FormStartPosition.CenterScreen; this.KeyPreview = true; this.AllowDrop = true; bar = new Panel(); bar.Dock = DockStyle.Top; bar.Height = 44; bar.BackColor = COL_BAR; int x = 10; x = AddBtn("打开", x, new EventHandler(OpenClick), true); x = AddBtn("◀ 上一张", x, new EventHandler(PrevClick), false); x = AddBtn("下一张 ▶", x, new EventHandler(NextClick), false); x = AddBtn("缩小", x, new EventHandler(ZoomOutClick), false); x = AddBtn("放大", x, new EventHandler(ZoomInClick), false); x = AddBtn("适应窗口", x, new EventHandler(FitClick), false); x = AddBtn("实际大小", x, new EventHandler(ActualClick), false); x = AddBtn("旋转", x, new EventHandler(RotateClick), false); AddBtn("幻灯片", x, new EventHandler(SlideClick), false); canvas = new CanvasPanel(); canvas.Dock = DockStyle.Fill; canvas.BackColor = COL_BG; canvas.Cursor = Cursors.Default; canvas.Paint += new PaintEventHandler(OnPaint); canvas.MouseDown += new MouseEventHandler(OnMouseDown); canvas.MouseMove += new MouseEventHandler(OnMouseMove); canvas.MouseUp += new MouseEventHandler(OnMouseUp); canvas.MouseWheel += new MouseEventHandler(OnWheel); canvas.MouseDoubleClick += new MouseEventHandler(OnDoubleClick); Panel bottom = new Panel(); bottom.Dock = DockStyle.Bottom; bottom.Height = 28; bottom.BackColor = COL_BAR; status = new Label(); status.Text = "拖入图片,或按「打开」选择(Ctrl+O)"; status.AutoSize = false; status.Dock = DockStyle.Fill; status.TextAlign = ContentAlignment.MiddleLeft; status.Padding = new Padding(10, 0, 10, 0); status.ForeColor = COL_DIM; bottom.Controls.Add(status); this.Controls.Add(canvas); this.Controls.Add(bar); this.Controls.Add(bottom); // Dock 布局按 z-order 逆序算,Fill 的必须排到最后(索引 0),否则会被工具条压住 this.Controls.SetChildIndex(canvas, 0); this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); this.KeyDown += new KeyEventHandler(OnKeyDown); this.FormClosing += new FormClosingEventHandler(OnClosing); } private int AddBtn(string text, int x, EventHandler h, bool primary) { Button b = new Button(); b.Text = text; b.Location = new Point(x, 8); b.Size = new Size(primary ? 64 : 84, 28); b.FlatStyle = FlatStyle.Flat; b.FlatAppearance.BorderSize = 1; b.FlatAppearance.BorderColor = primary ? COL_GREEN : Color.FromArgb(66, 70, 76); b.BackColor = primary ? COL_GREEN : COL_BAR; b.ForeColor = primary ? Color.White : COL_FG; b.TabStop = false; b.Click += h; bar.Controls.Add(b); return x + b.Width + 6; } // ===== 打开与加载 ===== private void OpenClick(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Title = "选择图片"; d.Filter = "图片|*.jpg;*.jpeg;*.jfif;*.png;*.bmp;*.gif;*.tif;*.tiff;*.ico|所有文件|*.*"; if (d.ShowDialog() == DialogResult.OK) OpenPath(d.FileName); } } private void OpenPath(string path) { if (Directory.Exists(path)) { string first = FirstImageIn(path); if (first == null) { SetText("这个文件夹里没有能看的图片"); return; } OpenPath(first); return; } if (!ViewOps.IsSupported(path)) { SetText("这个格式不支持(GDI+ 只认 jpg/png/bmp/gif/tiff/ico)"); return; } string dir = Path.GetDirectoryName(path); _files = ViewOps.ListImages(dir); if (_files.Count == 0) _files.Add(path); int at = -1; for (int i = 0; i < _files.Count; i++) { if (string.Equals(_files[i], path, StringComparison.OrdinalIgnoreCase)) { at = i; break; } } ShowAt(at >= 0 ? at : 0); } // 给命令行入口用(双击图片文件直接打开) public void OpenPathPublic(string path) { OpenPath(path); } private static string FirstImageIn(string dir) { List l = ViewOps.ListImages(dir); return l.Count > 0 ? l[0] : null; } private void ShowAt(int index) { if (index < 0 || index >= _files.Count) return; string path = _files[index]; Bitmap bmp = null; try { // 用流读再克隆:Image.FromFile 会把文件锁住,用户就删不掉/改不了 using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) using (Image tmp = Image.FromStream(fs)) { bmp = new Bitmap(tmp); int orient = ReadOrientation(tmp); ApplyOrientation(bmp, orient); } } catch (Exception ex) { SetText("打不开:" + ex.GetType().Name + " " + ex.Message); return; } if (_img != null) { _img.Dispose(); _img = null; } _img = bmp; _path = path; _idx = index; _rot = 0; _ox = 0; _oy = 0; _fit = true; Recompute(); canvas.Invalidate(); this.Text = Path.GetFileName(path) + " - 轻量看图"; UpdateStatus(); } // 手机拍的竖图常带 EXIF 方向标记,不按它转就会躺着看 private static int ReadOrientation(Image img) { try { PropertyItem p = img.GetPropertyItem(0x0112); if (p != null && p.Value != null && p.Value.Length >= 2) return p.Value[0]; } catch { } return 1; } private static void ApplyOrientation(Bitmap bmp, int o) { switch (o) { case 2: bmp.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: bmp.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: bmp.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: bmp.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: bmp.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: bmp.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: bmp.RotateFlip(RotateFlipType.Rotate270FlipNone); break; default: break; } } private void Recompute() { if (_img == null) { _zoom = 1.0; return; } if (_fit) { _zoom = ViewOps.FitZoom(_img.Width, _img.Height, canvas.ClientSize.Width, canvas.ClientSize.Height, 12); _ox = 0; _oy = 0; } } private void UpdateStatus() { if (_img == null) { SetText("拖入图片,或按「打开」选择(Ctrl+O)"); return; } long len = 0; try { len = new FileInfo(_path).Length; } catch { } SetText(ViewOps.InfoText(_path, _img.Width, _img.Height, len, _zoom, _idx, _files.Count)); } private void SetText(string s) { status.ForeColor = COL_DIM; status.Text = s; } // ===== 绘制 ===== private void OnPaint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.Clear(COL_BG); if (_img == null) { string hint = "把图片拖进来,或者点左上角「打开」"; using (Font f = new Font("Microsoft YaHei UI", 12f)) using (SolidBrush b = new SolidBrush(COL_DIM)) { SizeF sz = g.MeasureString(hint, f); g.DrawString(hint, f, b, (canvas.ClientSize.Width - sz.Width) / 2f, (canvas.ClientSize.Height - sz.Height) / 2f); } return; } double z = _zoom; float w = (float)(_img.Width * z); float h = (float)(_img.Height * z); float left = canvas.ClientSize.Width / 2f - w / 2f + _ox; float top = canvas.ClientSize.Height / 2f - h / 2f + _oy; RectangleF dest = new RectangleF(left, top, w, h); // 透明 PNG 底下垫棋盘格,纯黑背景上看不出哪里是透明的 if (HasAlpha(_img)) { DrawChecker(g, dest); } g.InterpolationMode = z >= 1.0 ? InterpolationMode.NearestNeighbor : InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.Half; g.SmoothingMode = SmoothingMode.None; try { g.DrawImage(_img, dest); } catch { } } private static bool HasAlpha(Image img) { try { return Image.IsAlphaPixelFormat(img.PixelFormat); } catch { return false; } } private static void DrawChecker(Graphics g, RectangleF r) { int cell = 14; Color c1 = Color.FromArgb(58, 60, 64); Color c2 = Color.FromArgb(46, 48, 52); using (SolidBrush b1 = new SolidBrush(c1)) using (SolidBrush b2 = new SolidBrush(c2)) { int x0 = (int)Math.Floor(r.Left); int y0 = (int)Math.Floor(r.Top); int x1 = (int)Math.Ceiling(r.Right); int y1 = (int)Math.Ceiling(r.Bottom); g.SetClip(r); for (int y = y0; y < y1; y += cell) { for (int x = x0; x < x1; x += cell) { bool odd = (((x - x0) / cell) + ((y - y0) / cell)) % 2 == 1; g.FillRectangle(odd ? b2 : b1, x, y, cell, cell); } } g.ResetClip(); } } // ===== 交互 ===== private void OnWheel(object sender, MouseEventArgs e) { if (_img == null) return; double factor = e.Delta > 0 ? 1.15 : 1 / 1.15; ZoomAround(factor, e.X, e.Y); } private void ZoomAround(double factor, int mx, int my) { double old = _zoom; double nz = ViewOps.ClampZoom(old * factor); if (Math.Abs(nz - old) < 0.0001) return; // 以光标为锚点缩放:光标底下的那一点保持不动 float cx = canvas.ClientSize.Width / 2f; float cy = canvas.ClientSize.Height / 2f; float ix = (mx - cx - _ox) / (float)old; float iy = (my - cy - _oy) / (float)old; _zoom = nz; _ox = mx - cx - (float)(ix * nz); _oy = my - cy - (float)(iy * nz); _fit = false; canvas.Invalidate(); UpdateStatus(); } private void OnMouseDown(object sender, MouseEventArgs e) { canvas.Focus(); if (_img == null) return; if (e.Button == MouseButtons.Left) { _dragging = true; _dragStart = e.Location; _dragOx = _ox; _dragOy = _oy; canvas.Cursor = Cursors.SizeAll; } } private void OnMouseMove(object sender, MouseEventArgs e) { if (!_dragging) return; _ox = _dragOx + (e.X - _dragStart.X); _oy = _dragOy + (e.Y - _dragStart.Y); canvas.Invalidate(); } private void OnMouseUp(object sender, MouseEventArgs e) { _dragging = false; canvas.Cursor = Cursors.Default; } private void OnDoubleClick(object sender, MouseEventArgs e) { ToggleFullscreen(); } private void OnKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape && _fullscreen) { ToggleFullscreen(); return; } if (e.Control && e.KeyCode == Keys.O) { OpenClick(null, null); return; } if (e.Control && e.KeyCode == Keys.C && _img != null) { try { Clipboard.SetImage(_img); SetText("已复制到剪贴板(原尺寸)"); } catch { SetText("复制失败:剪贴板被别的程序占用"); } return; } switch (e.KeyCode) { case Keys.Left: PrevClick(null, null); break; case Keys.Right: NextClick(null, null); break; case Keys.Up: case Keys.Oemplus: case Keys.Add: if (_img != null) ZoomAround(1.25, canvas.ClientSize.Width / 2, canvas.ClientSize.Height / 2); break; case Keys.Down: case Keys.OemMinus: case Keys.Subtract: if (_img != null) ZoomAround(1 / 1.25, canvas.ClientSize.Width / 2, canvas.ClientSize.Height / 2); break; case Keys.D0: case Keys.NumPad0: FitClick(null, null); break; case Keys.D1: case Keys.NumPad1: ActualClick(null, null); break; case Keys.R: RotateClick(null, null); break; case Keys.F: case Keys.F11: ToggleFullscreen(); break; case Keys.Space: SlideClick(null, null); break; default: return; } } private void ToggleFullscreen() { if (!_fullscreen) { _oldBorder = this.FormBorderStyle; _oldState = this.WindowState; _oldBounds = this.Bounds; this.FormBorderStyle = FormBorderStyle.None; this.WindowState = FormWindowState.Maximized; _fullscreen = true; } else { this.FormBorderStyle = _oldBorder; this.WindowState = FormWindowState.Normal; this.Bounds = _oldBounds; _fullscreen = false; } Recompute(); canvas.Invalidate(); } private void PrevClick(object sender, EventArgs e) { int n = ViewOps.Step(_idx, _files.Count, -1); if (n >= 0) ShowAt(n); } private void NextClick(object sender, EventArgs e) { int n = ViewOps.Step(_idx, _files.Count, 1); if (n >= 0) ShowAt(n); } private void ZoomInClick(object sender, EventArgs e) { if (_img != null) ZoomAround(1.25, canvas.ClientSize.Width / 2, canvas.ClientSize.Height / 2); } private void ZoomOutClick(object sender, EventArgs e) { if (_img != null) ZoomAround(1 / 1.25, canvas.ClientSize.Width / 2, canvas.ClientSize.Height / 2); } private void FitClick(object sender, EventArgs e) { if (_img == null) return; _fit = true; Recompute(); canvas.Invalidate(); UpdateStatus(); } private void ActualClick(object sender, EventArgs e) { if (_img == null) return; _fit = false; _zoom = 1.0; _ox = 0; _oy = 0; canvas.Invalidate(); UpdateStatus(); } private void RotateClick(object sender, EventArgs e) { if (_img == null) return; _img.RotateFlip(RotateFlipType.Rotate90FlipNone); _rot = (_rot + 90) % 360; Recompute(); canvas.Invalidate(); UpdateStatus(); } private void SlideClick(object sender, EventArgs e) { if (_files.Count <= 1) { SetText("至少要有两张图才能放幻灯片"); return; } slideTimer.Enabled = !slideTimer.Enabled; SetText(slideTimer.Enabled ? "幻灯片播放中(每 2.5 秒一张,空格暂停)" : "幻灯片已暂停"); } private void SlideTick(object sender, EventArgs e) { NextClick(null, null); } 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[] arr = (string[])e.Data.GetData(DataFormats.FileDrop); if (arr == null || arr.Length == 0) return; OpenPath(arr[0]); } private void OnClosing(object sender, FormClosingEventArgs e) { slideTimer.Stop(); if (_img != null) { _img.Dispose(); _img = null; } } } // 画布:开双缓冲,缩放拖动才不闪 public class CanvasPanel : Panel { public CanvasPanel() { this.DoubleBuffered = true; this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); this.TabStop = true; } protected override bool IsInputKey(Keys keyData) { // 方向键默认被当成「切换焦点」,这里要自己处理成翻页 if (keyData == Keys.Left || keyData == Keys.Right || keyData == Keys.Up || keyData == Keys.Down) return true; return base.IsInputKey(keyData); } } public static class ViewSelfTest { 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 ""; 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 CheckTrue(string name, bool ok, string detail) { Check(name, ok ? "yes" : "no", "yes"); if (!ok && detail != null) _lines.Add(" 详情:" + Esc(detail)); } public static int Run(string dir) { try { _lines.Add("轻量看图 自测"); _lines.Add("工作目录:" + dir); // ── 支持格式判定 ── CheckTrue("jpg 支持", ViewOps.IsSupported("a.jpg"), null); CheckTrue("扩展名大写也认", ViewOps.IsSupported("A.JPG"), null); CheckTrue("jpeg 支持", ViewOps.IsSupported("a.jpeg"), null); CheckTrue("png 支持", ViewOps.IsSupported("a.png"), null); CheckTrue("gif 支持", ViewOps.IsSupported("a.gif"), null); CheckTrue("tiff 支持", ViewOps.IsSupported("a.tiff"), null); CheckTrue("webp 不认(GDI+ 限制)", !ViewOps.IsSupported("a.webp"), null); CheckTrue("无扩展名不认", !ViewOps.IsSupported("readme"), null); CheckTrue("空路径不认", !ViewOps.IsSupported(""), null); CheckTrue("null 不认", !ViewOps.IsSupported(null), null); // ── 文件大小文案 ── Check("0 字节", ViewOps.FormatSize(0), "0 B"); Check("512 字节", ViewOps.FormatSize(512), "512 B"); Check("1023 字节仍是 B", ViewOps.FormatSize(1023), "1023 B"); Check("1024 变 KB", ViewOps.FormatSize(1024), "1.0 KB"); Check("1536 字节", ViewOps.FormatSize(1536), "1.5 KB"); Check("1MB", ViewOps.FormatSize(1048576), "1.00 MB"); Check("1.5MB", ViewOps.FormatSize(1572864), "1.50 MB"); Check("2GB", ViewOps.FormatSize(2147483648L), "2.00 GB"); Check("负数不崩", ViewOps.FormatSize(-1), "?"); // ── 缩放文案与夹取 ── Check("100%", ViewOps.ZoomText(1.0), "100%"); Check("33%", ViewOps.ZoomText(0.333), "33%"); Check("250%", ViewOps.ZoomText(2.5), "250%"); Check("0.05 下限", ViewOps.ClampZoom(0.001).ToString(CultureInfo.InvariantCulture), "0.05"); Check("0.05 本身不变", ViewOps.ClampZoom(0.05).ToString(CultureInfo.InvariantCulture), "0.05"); Check("8 倍上限", ViewOps.ClampZoom(100).ToString(CultureInfo.InvariantCulture), "8"); Check("正常值不动", ViewOps.ClampZoom(1.7).ToString(CultureInfo.InvariantCulture), "1.7"); // ── 适应窗口 ── double f1 = ViewOps.FitZoom(2000, 1000, 800, 600, 12); Check("2000x1000 进 800x600(宽度先顶住)", f1.ToString("0.000", CultureInfo.InvariantCulture), "0.388"); double f2 = ViewOps.FitZoom(1000, 2000, 800, 900, 12); Check("1000x2000 进 800x900(高度先顶住)", f2.ToString("0.000", CultureInfo.InvariantCulture), "0.438"); Check("小图不放大", ViewOps.FitZoom(100, 100, 800, 600, 12).ToString(CultureInfo.InvariantCulture), "1"); Check("尺寸非法时退回 100%", ViewOps.FitZoom(0, 0, 800, 600, 12).ToString(CultureInfo.InvariantCulture), "1"); // ── 翻页绕回 ── Check("第一张往前 → 最后一张", ViewOps.Step(0, 5, -1).ToString(), "4"); Check("最后一张往后 → 第一张", ViewOps.Step(4, 5, 1).ToString(), "0"); Check("没打开时往后", ViewOps.Step(-1, 5, 1).ToString(), "0"); Check("空列表返回 -1", ViewOps.Step(0, 0, 1).ToString(), "-1"); // ── 自然排序 ── List names = new List(); names.Add("图10.png"); names.Add("图2.png"); names.Add("图1.png"); names.Sort(delegate(string a, string b) { return ViewOps.NaturalCompare(a, b); }); Check("图1 < 图2 < 图10", string.Join(",", names.ToArray()), "图1.png,图2.png,图10.png"); CheckTrue("字母不区分大小写", ViewOps.NaturalCompare("B.png", "a.png") > 0, null); CheckTrue("纯数字 9 < 10", ViewOps.NaturalCompare("9", "10") < 0, null); Check("相等返回 0", ViewOps.NaturalCompare("abc", "abc").ToString(), "0"); CheckTrue("前缀短的排前", ViewOps.NaturalCompare("abc", "abcd") < 0, null); // ── 状态栏文案 ── Check("状态栏完整文案", ViewOps.InfoText(@"C:\pics\海边.jpg", 1920, 1080, 1572864, 1.0, 2, 9), "海边.jpg · 1920 × 1080 · 1.50 MB · 100% · 3/9"); Check("单张不显示序号", ViewOps.InfoText(@"C:\a.png", 10, 20, 0, 0.5, 0, 1), "a.png · 10 × 20 · 50%"); // ── 真实文件:建图 → 列表 → 排序 → 读回尺寸 ── Directory.CreateDirectory(dir); string d2 = Path.Combine(dir, "pics"); if (Directory.Exists(d2)) Directory.Delete(d2, true); Directory.CreateDirectory(d2); MakeImage(Path.Combine(d2, "图10.png"), 120, 60, ImageFormat.Png); MakeImage(Path.Combine(d2, "图2.jpg"), 200, 100, ImageFormat.Jpeg); MakeImage(Path.Combine(d2, "图1.bmp"), 30, 40, ImageFormat.Bmp); File.WriteAllText(Path.Combine(d2, "说明.txt"), "不是图片"); List found = ViewOps.ListImages(d2); Check("只收图片文件", found.Count.ToString(), "3"); Check("按自然顺序列目录", Path.GetFileName(found[0]) + "|" + Path.GetFileName(found[1]) + "|" + Path.GetFileName(found[2]), "图1.bmp|图2.jpg|图10.png"); using (Image im = Image.FromFile(Path.Combine(d2, "图2.jpg"))) { Check("jpg 能解码且尺寸正确", im.Width + "x" + im.Height, "200x100"); // 旋转 90° 后宽高必须互换,这是「旋转」按钮的唯一硬指标 im.RotateFlip(RotateFlipType.Rotate90FlipNone); Check("旋转 90° 宽高互换", im.Width + "x" + im.Height, "100x200"); } // 透明 PNG 要能被识别,否则棋盘格垫不上 string pngA = Path.Combine(dir, "alpha.png"); using (Bitmap b = new Bitmap(20, 20, PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(b)) { g.Clear(Color.Transparent); } b.Save(pngA, ImageFormat.Png); } using (Image ia = Image.FromFile(pngA)) { CheckTrue("透明 PNG 识别为带 alpha", Image.IsAlphaPixelFormat(ia.PixelFormat), ia.PixelFormat.ToString()); } // 打不开的假图片要能给出异常,而不是静默空白 string bad = Path.Combine(dir, "坏文件.jpg"); File.WriteAllText(bad, "这不是 jpeg"); bool threw = false; try { using (FileStream fs = new FileStream(bad, FileMode.Open, FileAccess.Read)) using (Image t = Image.FromStream(fs)) { } } catch { threw = true; } CheckTrue("伪造的 jpg 会抛异常(界面能提示)", threw, null); } 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-imgview.txt"), all, new System.Text.UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } private static void MakeImage(string path, int w, int h, ImageFormat fmt) { using (Bitmap b = new Bitmap(w, h)) { using (Graphics g = Graphics.FromImage(b)) { g.Clear(Color.FromArgb(0, 145, 88)); g.FillEllipse(Brushes.White, w / 4, h / 4, w / 2, h / 2); } b.Save(path, fmt); } } } public static class Program { [STAThread] public static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(ViewSelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); ImageViewerForm f = new ImageViewerForm(); // 命令行带图片路径时直接打开,方便设成「双击 jpg 的默认程序」 if (args != null && args.Length > 0 && File.Exists(args[0])) { f.Shown += delegate { f.OpenPathPublic(args[0]); }; } Application.Run(f); } } }