我正在加载一个Image
from a byte[]
using 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");
Output:
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");
Output:
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
是在这种情况下处置的吗?