WPF中的BitmapImage类是UI控件类,是.net对象,使用完毕不需要Dispose或close来对其释放资源;需要在UI线程上对其进行操作,不能再其他线程上对其进行操作,否则会报错。
该类继承于DispatcherObject,其继承链如下所示:
Object->DispatcherObject->DependencyObject->Freezable->Animatable->ImageSource->BitmapSource->BitmapImage
可以将其用于Image控件的Source属性,通常该Source属性可以简单的用路径来设置,比如<Image Source="c://123.jpg" />,但是,当对123.jpg频繁进行修改时,会存在123.jpg文件被进程占用的异常。这时可以采用BitmapImage对象来绑定。比如:
<Image Source="{Binding BitmapImageSource}"/>
在VM中创建BitmapImageSource属性,比如:
private BitmapImage _bitmapImageSouce;
public BitmapImage BitmapImageSource
{
get
{
return _bitmapImageSource;
}
set
{
if(_bitmapImageSource!=value)
{
_bitmapImageSource=value;
OnPropertyChanged("BitmapImageSouce");
}
}
}
进而,可以在代码中对BitmapImageSource对象进行赋值。为了避免赋值后的文件被进程占用,可以先将文件读入MemoryStream对象,然后关键文件,再利用MemoryStream对象来构件BitmapImage对象,比如:
//把方法运行效果很好,达到了可以频繁显示经更改数据(但照片路径不变)后的照片的目的
private BitmapImage GetBitmapImage(string imagePath)
{
FileStream fs = null;
try
{
fs = new FileStream(imagePath, FileMode.Open);
byte[] MyData = new byte[fs.Length];
fs.Read(MyData, 0, (int)fs.Length);
MemoryStream ms = new MemoryStream(MyData);
BitmapImage bitmap = new BitmapImage(); //WPF
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = ms;
bitmap.EndInit();
return bitmap;
}
catch (Exception ex)
{
// Exception treatment code here
return null;
}
finally
{
if (fs != null)
fs.Close();
}
}
有些网上介绍的方法,没有使用MemoryStream来创建BitmapImage,而是直接给BitmapImage赋UriSource值,并克隆初始创建的
BitmapImage对象,经实际使用,若多次修改照片数据但照片路径保持不变的情况下,存在不能更新显示的Image,且偶尔也会发生文件被占用的情况。其代码如下:
//注意,以下代码达到不想要的效果,若照片数据需要修改,则不会及时反映到显示的照片中,这种情况下是不能使用本方法的
try
{
BitmapImage bitmap = new BitmapImage(); //WPF
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.UriSource =new Uri(myImagePath);
bitmap.EndInit();
return bitmap.Clone(); //返回克隆对象
}
catch (Exception ex)
{
// Exception treatment code here
return null;
}