使用Image控件显示图片后,虽然自己释放了图片资源,Image.Source =null 了一下,但是图片实际没有释放。
解决方案1:
public static BitmapImage GetImage(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;
}
//使用时直接通过调用此方法获得Image后立马释放掉资源
image1.Source = GetImage(path); // path为图片路径
解决方案2:
BitmapImage bitmapImage = new BitmapImage(); //初始化BitmapImage类的一个新实例
Image image1 = new Image(); //定义一个Image控件
string strPath = "D:\\mImage.png";//图片所在的位置
bitmapImage.BeginInit(); //表示BitmapImage初始化开始
bitmapImage.CacheOption = BitmapCacheOption.Onload;
bitmapImage.UriSource = new Uri(strPath);//获取或设置BitmapImage的Uri源
bitmapImage.EndInit();//表示BitmapImage初始化结束
image1.Source = bitmapImage;//将image1控件的源指定为bitmapImage