我有这个函数,它在使用 Image.FromStream 方法创建图像的函数中返回一个图像根据 MSDN:
<块引用>您必须在图像的生命周期内保持流打开
所以我不会关闭流(如果我确实关闭了流,则从返回的图像对象中抛出 GDI+ 异常).我的问题是当 Image.Dispose() 在返回的图像上的其他地方被调用时,流是否会关闭/处置
public static Image GetImage(byte[] buffer, int offset, int count){var memoryStream = new MemoryStream(buffer, offset, count);返回 Image.FromStream(memoryStream);}
正如其中一个答案所建议的那样,使用不是可行的方法,因为它会引发异常:
public static Image GetImage(byte[] buffer, int offset, int count){使用(var memoryStream = new MemoryStream(缓冲区,偏移量,计数)){返回 Image.FromStream(memoryStream);}}public static void Main(){var image = GetImage(args);图像.保存(路径);<-- 抛出异常}
尽管其他人建议这样做,但在处理图像之前,您不应关闭或处理流.
MSDN 指出:><块引用>
您必须在图像的整个生命周期内保持流打开.
对于某些流,例如 MemoryStream
,处置没有太大用处,因为它不分配非托管资源.另一方面,文件流会这样做,因此除非您非常确定流是安全的,否则您应该始终在处理完图像后处理流.
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.
这篇关于返回由 Image.FromStream(Stream stream) 方法创建的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!