提問者提到「mpf 窗體」,實為 WPF (Windows Presentation Foundation) 的筆誤。WPF 與 WinForms 架構截然不同,圖片顯示方式也有所差異。
<Window x:Class="WpfApp.MainWindow"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
Title="圖片顯示範例" Height="450" Width="800">
<Grid>
<Image x:Name="imgPhoto" Stretch="Uniform" Margin="10"/>
</Grid>
</Window>
using System.Windows.Media.Imaging;
using System.IO;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadImage(@"C:\Photos\sample.jpg");
}
private void LoadImage(string path)
{
if (!File.Exists(path)) return;
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad; // 讀取後釋放檔案鎖定
bitmap.UriSource = new Uri(path, UriKind.Absolute);
bitmap.EndInit();
bitmap.Freeze(); // 跨執行緒安全
imgPhoto.Source = bitmap;
}
}
CacheOption.OnLoad 會導致檔案被佔用,無法覆寫或刪除。pack://application:,,,/Images/photo.jpg 格式 URI。DecodePixelWidth/Height 縮小解碼尺寸,避免 OOM。官方範例:WPF 如何載入點陣圖