Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image.FromStream does not hold a ref to the underlying stream

Tags:

c#

.net

image

I have some code that does

MemoryStream ms = new MemoryStream();
...
return Image.FromStream(ms);

It fails in very eclectic ways since the Image object does not hold a ref to the stream, so it can get disposed if the GC kicks in which results in GDI+ errors.

How do I work around this (without saving the stream to disk, or altering my method sigs) ?

like image 503
Sam Saffron Avatar asked Dec 21 '25 00:12

Sam Saffron


2 Answers

This seems highly unlikely to me - it would cause a problem for almost any use of Image.FromStream.

It seems more likely to me that something's disposing of your MemoryStream, which it shouldn't.

Could you provide a short but complete program which demonstrates the problem? Forcing garbage collection should make it relatively easy to reproduce - you could even create your own class deriving from MemoryStream with a finalizer to show whether or not it really is being collected (well, finalized at least).

like image 123
Jon Skeet Avatar answered Dec 24 '25 11:12

Jon Skeet


There isn't a way to do it without changing your code somewhat. The Remarks section for the documentation for the static FromStream method on the Image class states:

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

That being said, you have to make sure that while the Image is accessing the Stream, the stream is open. It would also appear (looking through Reflector) that the FromImage method doesn't actually cause the Image instance to hold onto a reference to the Stream the image was loaded from.

That being said, you to somehow link the image and the MemoryStream (or Stream) together so that it doesn't get GCed. If don't really retain "ownership" of the image (it is passed around), then I recommend that you create a data structure which will hold the reference to the Image and to the Stream and pass the two around in tandem.

like image 43
casperOne Avatar answered Dec 24 '25 10:12

casperOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!