Uthistran Selvaraj.
Uthistran Selvaraj.

Reputation: 558

How to dispose a stream after using it in Image?

I have the stream of the Image and I convert it into image by the below code

Image imagefromstream = Image.FromStream(stream);

When I draw this image in graphics, it draws the image.

But, if I dispose the stream after drawing in graphics, the image is not drawn.

Can anyone help me to dispose the image stream

Upvotes: 5

Views: 2943

Answers (2)

Sankarann
Sankarann

Reputation: 2665

In this case, you have the direct reference of memory stream and if you dispose it, image also will get disposed.

So you get the source from the stream and have it in a BitmapImage, set that BitmapImage as the source for the Image..

var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.StreamSource = memoryStream;
imageSource.CacheOption= CacheOption.OnLoad;
imageSource.EndInit();

// Assign the Source property of your image
image.Source = imageSource;

Upvotes: 3

Baldrick
Baldrick

Reputation: 11840

According to MSDN here:

You must keep the stream open for the lifetime of the Image.

You'll have to Dispose the stream when you close your application (or whenever you no longer need the Image)

Upvotes: 9

Related Questions