views:

89

answers:

3

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.

A: 

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;
Ivan Ferić
No, that is not my problem, image is not being loaded at all from the source, that's what my problem at the moment is... :(
Thorinair
A: 

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.

rossisdead
So, what should I do? You should note that I started programming in C# 1 day ago...
Thorinair
A: 

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!

Thorinair