I have this function which returns an Image within the function the image is created using the Image.FromStream method According to MSDN:
You must keep the stream open for the lifetime of the Image
So I'm not closing the stream(if I do close the steam a GDI+ exception is thrown from the returned image object). My question is whether the stream will be closed/disposed when Image.Dispose() is called somewhere else on the returned Image
public static Image GetImage(byte[] buffer, int offset, int count)
{
var memoryStream = new MemoryStream(buffer, offset, count);
return Image.FromStream(memoryStream);
}
As suggested in one of the answers, using is not the way to go, since it throws an exception:
public static Image GetImage(byte[] buffer, int offset, int count)
{
using(var memoryStream = new MemoryStream(buffer, offset, count))
{
return Image.FromStream(memoryStream);
}
}
public static void Main()
{
var image = GetImage(args);
image.Save(path); <-- Throws exception
}
Despite what others advice to do, you should not close or dispose the stream until the image is disposed.
MSDN states:
You must keep the stream open for the lifetime of the Image.
For some streams, like MemoryStream
, disposing doesn't have much use since it doesn't allocate unmanaged resources. File streams on the other hand do, so unless you are very sure the stream is safe, you should always dispose the stream when you are done with the image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With