我正在Image
从byte[]
使用中加载一个MemoryStream
并通过检查它来获取有关图像的信息ProperyItems
。不过,在执行此操作的过程中,我注意到一些奇怪的行为,其中一些图像PropertyItems
正在消失。经过多次调试,我终于发现这是由MemoryStream
被处置引起的。
MemoryStream ms0 = new MemoryStream(imageBytes);
Image img0 = Image.FromStream(ms0);
Console.Out.WriteLine("Without using, Image propertyIDs: ");
foreach (int itemId in img0.PropertyIdList)
Console.Out.Write(itemId + ", ");
Console.Out.Write("\n");
Image img1 = null;
using (MemoryStream ms1 = new MemoryStream(imageBytes))
{
img1 = Image.FromStream(ms1);
}
Console.Out.WriteLine("Outside using, Image propertyIDs: ");
foreach (int itemId in img1.PropertyIdList)
Console.Out.Write(itemId + ", ");
Console.Out.Write("\n");
输出:
Without using, Image propertyIDs:
254, 256, 257, 258, 259, 262, 269, 273, 274, 277, 278, 279, 282, 283, 284, 296,
Outside using, Image propertyIDs:
254, 256, 257, 258, 259, 262, 274, 277, 278, 284, 296,
所以看起来至少有一些PropertyItems
是直接由内容支持的,MemoryStream
解决方案是不处理它,还是我错了?
在调试此问题的过程中,虽然我注意到其他一些奇怪的事情,但如果我访问块内的PropertyIdList
(或与图像相关的任何内容PropertyItems
) ,则在处理后不会消失。using
PropertyItems
MemoryStream
Image img2 = null;
using (MemoryStream ms2 = new MemoryStream(imageBytes))
{
img2 = Image.FromStream(ms2);
int[] tmp = img2.PropertyIdList;
}
Console.Out.WriteLine("Outside using with PropertyIdList access, Image propertyIDs: ");
foreach (int itemId in img2.PropertyIdList)
Console.Out.Write(itemId + ", ");
Console.Out.Write("\n");
输出:
Outside using with PropertyIdList access, Image propertyIDs:
254, 256, 257, 258, 259, 262, 269, 273, 274, 277, 278, 279, 282, 283, 284, 296,
我查看了Image
该类的源,并且该PropertyIdList
属性似乎没有保留PropertyItems
数据的本地副本,那么为什么在这种情况下处置PropertyItems
后保留?MemoryStream