在BitmapImage.EndInit中抛出OutOfMemoryException:
public static BitmapImage GetResourceImage(string resourcePath,int decodePixelWidth = 0,int decodePixelHeight = 0) { var image = new BitmapImage(); var moduleName = Assembly.GetExecutingAssembly().GetName().Name; var resourceLocation = string.Format("pack://application:,/{0};component/Resources/{1}",moduleName,resourcePath); image.BeginInit(); image.UriSource = new Uri(resourceLocation); image.DecodePixelWidth = decodePixelWidth; image.DecodePixelHeight = decodePixelHeight; image.EndInit(); image.Freeze(); return image; }
>崩溃过程的任务管理器读数:27MB内存,302个句柄,12个线程,36个用户对象,34个GDI对象,5.3 GB RAM可用
>平台目标是x86(因本机DLL使用而需要)
>对于不同的(随机)图像,方法被多次调用(资源中有大约250个bmp文件)
> decodePixelWidth / Height是随机的,但在有效范围内
>异常发生在不同的资源路径和大小上
>仅当DecodePixelWidth或DecodePixelHeight不为0时才会发生异常
>如果我注释掉DecodePixelWidth和DecodePixelHeight setter并将其加载到原始大小,则不会发生异常
据我通过谷歌搜索了解,它与GDI内部有关,但我找不到修复或解决方法.任何想法(除了使用一些其他机制来解码和/或调整图像大小 – 我只需要原始像素数据)?
完整的项目源代码可以在这里找到(链接到相关文件):https://code.google.com/p/lander-net/source/browse/trunk/csharp/LanderNet/Util/BitmapUtils.cs
更新:
我试图使用TransformedBitmap进行大小调整,它失败并出现相同的异常.
解决方法
在GDI中看起来像一个非常奇怪的错误,有256个颜色的位图(我的所有图像都是从我在QBasic写的学校时代游戏中获得的256色位图).
> png和24位位图没有问题
>加载24位位图后,调整256色位图的问题似乎消失了
错误发布到Microsoft Connect:https://connect.microsoft.com/VisualStudio/feedback/details/812641/bitmapsource-fails-with-outofmemoryexception-on-8-bit-bitmaps
下面是代码.
internal class Program { public static BitmapSource GetResourceImage(string resourcePath,resourcePath); image.BeginInit(); image.UriSource = new Uri(resourceLocation); image.DecodePixelWidth = decodePixelWidth; image.DecodePixelHeight = decodePixelHeight; image.EndInit(); image.Freeze(); return image; } private static void Main() { new Application(); // register pack uri scheme //GetResourceImage("Z40100.png"); //GetResourceImage("Z40100.bmp"); //GetResourceImage("Z40100_256color.bmp"); //GetResourceImage("Z40100_24bit.bmp"); // Uncomment the following line to fix the crash (or any of the two lines above) //GetResourceImage("Z40100_24bit.bmp",50,50); //GetResourceImage("Z40100_256color.bmp",50); GetResourceImage("Z40100.bmp",50); // GetResourceImage("Z40100.png",50); } }