應用場景
- 圖片瀏覽器:上一張/下一張動態切換
- 即時預覽:使用者選擇檔案後立即顯示
- 記憶體管理:及時釋放大型影像避免 OOM
- 動畫/輪播:定時器驅動圖片更換
WinForms 完整實作
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
public partial class DynamicImageForm : Form
{
private PictureBox _pic;
private Button _btnLoad, _btnRemove, _btnNext;
private string[] _imageFiles;
private int _currentIndex = -1;
public DynamicImageForm()
{
InitializeComponent();
SetupUI();
}
private void SetupUI()
{
_pic = new PictureBox
{
Dock = DockStyle.Fill,
SizeMode = PictureBoxSizeMode.Zoom,
BackColor = Color.Gray
};
Controls.Add(_pic);
var pnl = new FlowLayoutPanel { Dock = DockStyle.Bottom, Height = 50, FlowDirection = FlowDirection.RightToLeft };
_btnLoad = new Button { Text = "載入資料夾", AutoSize = true };
_btnRemove = new Button { Text = "移除圖片", AutoSize = true, Enabled = false };
_btnNext = new Button { Text = "下一張", AutoSize = true, Enabled = false };
pnl.Controls.AddRange(new Control[] { _btnNext, _btnRemove, _btnLoad });
Controls.Add(pnl);
_btnLoad.Click += BtnLoad_Click;
_btnRemove.Click += BtnRemove_Click;
_btnNext.Click += BtnNext_Click;
}
private void BtnLoad_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
_imageFiles = Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.TopDirectoryOnly)
.Where(f => IsImageFile(f)).ToArray();
_currentIndex = -1;
BtnNext_Click(null, null); // 載入第一張
}
}
}
private bool IsImageFile(string path)
{
string ext = Path.GetExtension(path).ToLowerInvariant();
return ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".gif" || ext == ".tiff";
}
private void BtnNext_Click(object sender, EventArgs e)
{
if (_imageFiles == null || _imageFiles.Length == 0) return;
_currentIndex = (_currentIndex + 1) % _imageFiles.Length;
LoadImage(_imageFiles[_currentIndex]);
_btnRemove.Enabled = true;
_btnNext.Enabled = true;
}
private void LoadImage(string path)
{
// 1. 釋放舊圖片
if (_pic.Image != null)
{
_pic.Image.Dispose();
_pic.Image = null;
}
// 2. 載入新圖片 (使用 FileStream 避免檔案鎖定)
try
{
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
_pic.Image = Image.FromStream(fs);
}
Text = $"動態圖片檢視 - {Path.GetFileName(path)} ({_currentIndex + 1}/{_imageFiles.Length})";
}
catch (Exception ex)
{
MessageBox.Show($"載入失敗: {ex.Message}", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void BtnRemove_Click(object sender, EventArgs e)
{
if (_pic.Image != null)
{
_pic.Image.Dispose();
_pic.Image = null;
_btnRemove.Enabled = false;
Text = "動態圖片檢視 - (無圖片)";
}
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
_pic.Image?.Dispose();
base.OnFormClosing(e);
}
}
WPF 版本 (MVVM 友善)
InitializeComponent();
private void BtnLoad_Click(object sender, RoutedEventArgs e)
{
var dlg = new System.Windows.Forms.FolderBrowserDialog(); // 需參考 System.Windows.Forms
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
_files = Directory.GetFiles(dlg.SelectedPath, "*.*")
.Where(f => IsImage(f)).ToArray();
_idx = -1;
BtnNext_Click(null, null);
}
}
private bool IsImage(string path)
{
string ext = Path.GetExtension(path).ToLower();
return ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".bmp" || ext == ".gif";
}
private void BtnNext_Click(object sender, RoutedEventArgs e)
{
if (_files == null || _files.Length == 0) return;
_idx = (_idx + 1) % _files.Length;
LoadImage(_files[_idx]);
}
private void LoadImage(string path)
{
try
{
// WPF 使用 BitmapImage,支援 URI 直接載入且不鎖定檔案
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad; // 完整載入記憶體,釋放檔案鎖定
bitmap.UriSource = new Uri(path, UriKind.Absolute);
bitmap.EndInit();
bitmap.Freeze(); // 跨執行緒安全、效能更好
imgDisplay.Source = bitmap;
Title = $"動態圖片 - {Path.GetFileName(path)} ({_idx + 1}/{_files.Length})";
}
catch (Exception ex)
{
MessageBox.Show($"載入失敗: {ex.Message}");
}
}
private void BtnRemove_Click(object sender, RoutedEventArgs e)
{
imgDisplay.Source = null;
GC.Collect(); // 建議釋放非受控資源
}
}
關鍵差異對比
| 特性 | WinForms (System.Drawing) | WPF (WPF Imaging) |
| 影像物件 | Bitmap / Image | BitmapImage / WriteableBitmap |
| 檔案鎖定 | Image.FromFile 鎖定檔案 → 需 FileStream 複製 | BitmapCacheOption.OnLoad 可不鎖定檔案 |
| 非受控資源 | 必須手動 Dispose() | 自動 GC,Freeze() 釋放非受控 |
| UI 執行緒 | 單執行緒 | Dispatcher 執行緒,Freeze() 後可跨執行緒 |
| 高 DPI | 需手動縮放 | 內建裝置無關像素 (DIP) 自動縮放 |
記憶體管理最佳實踐
- 立即釋放:不再使用的
Image/Bitmap 立即呼叫 Dispose()。
- 避免記憶體尖峰:大量圖片輪播時,預載入鄰近幀,其餘延遲載入。
- 使用弱參考快取:
WeakReference<Bitmap> 讓 GC 在記憶體壓力下回收。
- 大圖分塊載入:
ImageSharp / SkiaSharp 支援串流解碼,不需完整載入記憶體。