Why is the streaming image source not working?

I use the following code for the image source stream:

BitmapImage Art3 = new BitmapImage(); using (FileStream stream = File.OpenRead("c:\\temp\\Album.jpg")) { Art3.BeginInit(); Art3.StreamSource = stream; Art3.EndInit(); } artwork.Source = Art3; 

"artwork" is the XAML object in which the image should be displayed. The code should not block the image, it does not block it in order, but does not display it, and the default image becomes โ€œnothingโ€ ... I assume that I am using the stream incorrectly and that my image becomes null. Help?

UPDATE:

Now I use the following code that a friend suggested to me:

  BitmapImage Art3 = new BitmapImage(); FileStream f = File.OpenRead("c:\\temp\\Album.jpg"); MemoryStream ms = new MemoryStream(); f.CopyTo(ms); f.Close(); Art3.BeginInit(); Art3.StreamSource = ms; Art3.EndInit(); artwork.Source = Art3; 

For some strange reason, this code returns the following error:

Image cannot be decoded. Image title may be corrupted.

What am I doing wrong? I am sure that the image I'm trying to download is not corrupted.

+4
source share
4 answers

I managed to solve the problem using the following code:

  BitmapImage Art3 = new BitmapImage(); FileStream f = File.OpenRead("c:\\temp\\Album.jpg"); MemoryStream ms = new MemoryStream(); f.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); f.Close(); Art3.BeginInit(); Art3.StreamSource = ms; Art3.EndInit(); artwork.Source = Art3; 

Thanks to everyone who tried to help me!

+8
source

Eliminating the original stream will cause BitmapImage to no longer display everything that was in the stream. You will have to track the stream and get rid of it when you no longer use BitmapImage.

+1
source

It is probably easier

 BitmapImage Art3 = new BitmapImage(new Uri("file:///c:/temp/Album.jpg")); 
+1
source

You tried:

  BitmapImage Art3 = new BitmapImage(); using (FileStream stream = File.OpenRead("c:\\temp\\Album.jpg")) { Art3.BeginInit(); Art3.StreamSource = stream; stream.Flush(); Art3.EndInit(); } artwork.Source = Art3; 
0
source

All Articles