在WPF中外部加载图片,加载显示完成后释放,返回BitmapImage 可以直接赋值给wpf控件的ImageSource.
public static BitmapImage LoadImageFreeze(string imagePath)
{
try
{
BitmapImage bitmap = new BitmapImage();
if (File.Exists(imagePath))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))
{
bitmap.StreamSource = ms;
bitmap.EndInit();
bitmap.Freeze();
}
}
return bitmap;
}
catch (Exception)
{
return null;
}
}