相关:http://blog.sina.com.cn/s/blog_3f2c72ea0100srdg.html
场景:
WPF下用Image控件展示图片;
控件的图片源自然选用BitmapImage;
BitmapImage通过Uri对象指向磁盘的某个文件。
显示正常,但是这时候如果我们再有别的地方要操作这个磁盘文件,比如程序中或者其他地方,就会说资源已被占用。
资源无法释放的加载方式为:
_selectedColor = "/Image/pencil_strokes.png";
ImageSource imageSource = new BitmapImage(new Uri(_selectedColor));
解决方案:
ImageSource imageSource = AppHelper.GetBitmapImage(new Uri(Path.GetDirectoryName(Application.ResourceAssembly.Location) + @_selectedColor, UriKind.Absolute).AbsolutePath);
public static BitmapImage GetBitmapImage(string imagePath)
{
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;
}
网友评论