我有这个函数,它在使用 Image.FromStream 方法创建图像的函数中返回一个图像 根据MSDN :
You must keep the stream open for the lifetime of the Image
所以我没有关闭流(如果我确实关闭了流,则会从返回的图像对象中抛出 GDI+ 异常)。我的问题是,当在返回图像的其他地方调用 Image.Dispose() 时,流是否会被关闭/处置
public static Image GetImage(byte[] buffer, int offset, int count)
{
var memoryStream = new MemoryStream(buffer, offset, count);
return Image.FromStream(memoryStream);
}
正如其中一个答案所建议的那样,使用 不是可行的方法,因为它会引发异常:
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
}
- 根据某些人的说法,处置/关闭 MemoryStream 不是必需的,因为它不使用任何非托管资源,其他人则说相反的话,所以这是一种两难选择.
- Image.Dispose 方法不处理创建图像的流
- Image 类不包含对传递给 Image.FromStream 方法的 Stream 的任何引用,因此流最终会被 GC 收集...?因此 Image.Save 方法中的异常
- 返回一个包装类,其中包含对流的引用和由它创建的图像,从而使我们能够处理它们两者......?或者简单地使用 Tag 属性来保留对父流的引用...?
- 这个问题似乎只发生在使用MemoryStream 时。如果图像是从 ConnectStream 创建的,那么即使父流被释放,也不会发生任何坏。
最佳答案
无论其他人如何建议,在处理图像之前,您不应该关闭或处理流。
MSDN状态:
You must keep the stream open for the lifetime of the Image.
对于某些流,如 MemoryStream
,disposing 没有太多用处,因为它不分配非托管资源。另一方面,文件流会这样做,因此除非您非常确定流是安全的,否则在处理完图像后应始终处置流。
关于c# - 返回由 Image.FromStream(Stream stream) 方法创建的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25187162/