Thorinair
Thorinair

Reputation: 191

Why is streaming source of an image not working?

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.

Upvotes: 7

Views: 9941

Answers (4)

user2352580
user2352580

Reputation: 5

This is probably simplier

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

Upvotes: 1

Thorinair
Thorinair

Reputation: 191

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!

Upvotes: 12

rossisdead
rossisdead

Reputation: 2098

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.

Upvotes: 1

Ivan Ferić
Ivan Ferić

Reputation: 4763

Have 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;

Upvotes: 0

Related Questions