Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 340
Uthistran Selvaraj. Avatar asked Feb 25 '14 09:02

Uthistran Selvaraj.


2 Answers

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)

like image 163
Baldrick Avatar answered Oct 31 '22 21:10

Baldrick


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;
like image 37
Sankarann Avatar answered Oct 31 '22 20:10

Sankarann