Convert MemoryStream to BitmapImage thrown “System.NullReferenceException”
雨晨 金
1
Reputation point
I am trying to use TagLib to load album art dynamically to Image in WPF. So ,I define a dependency property like this:
public static readonly DependencyProperty AlbumImageProperty = DependencyProperty.Register(
"AlbumImage", typeof(BitmapImage), typeof(MainWindow), new PropertyMetadata(default(BitmapImage)));
public BitmapImage AlbumImage
{
get { return (BitmapImage) GetValue(AlbumImageProperty); }
set { SetValue(AlbumImageProperty, value); }
}
Then,I write a method to set the image:
private void SetAlbum(string path)
{
var file = TagLib.File.Create(path);
if (file.Tag.Pictures.Length >= 1)
{
MemoryStream ms=new MemoryStream(file.Tag.Pictures[0].Data.Data);
AlbumImage = new BitmapImage();
AlbumImage.BeginInit();
AlbumImage.StreamSource = ms;
AlbumImage.CacheOption = BitmapCacheOption.OnLoad;
AlbumImage.EndInit();
}
}
In the end,I binding it to MainWindow like this:
<Image Name="ImgAlbum" Source="{Binding AlbumImage}" HorizontalAlignment="Left" UseLayoutRounding="True"/>
But it thrown "System.NullReferenceException" when running to "AlbumImage.EndInit". When I didn't use dependency property to define "AlbumImage" , it can running without throwing Exception , but it also can't update image in MainWindow when the image source is changed.
What should I do to solve it? Thanks.