Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is streaming source of an image not working?

Tags:

c#

stream

image

wpf

I am using the following code to stream an image source:

        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 where image is supposed to be shown. The code is supposed not to lock up the image, it doesn't lock it up alright, but doesn't show it either and the default image becomes "nothing"... My guess is that I am not properly using the stream, and that my image becomes null. Help?

UPDATE:

I am now using the following code which 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:

The image cannot be decoded. The image header might be corrupted.

What am I doing wrong? I am sure the image I am trying to load is not corrupt.

like image 937
Thorinair Avatar asked Sep 10 '10 21:09

Thorinair


3 Answers

I managed to solve the problem by 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 everyone who tried to help me!

like image 67
Thorinair Avatar answered Sep 21 '22 21:09

Thorinair


Disposing the source stream will cause the BitmapImage to no longer display whatever was in the stream. You'll have to keep track of the stream and dispose of it when you're no longer using the BitmapImage.

like image 1
rossisdead Avatar answered Sep 20 '22 21:09

rossisdead


This is probably simplier

BitmapImage Art3 = new BitmapImage(new Uri("file:///c:/temp/Album.jpg"));
like image 1
user2352580 Avatar answered Sep 20 '22 21:09

user2352580