简体   繁体   English

在目标为AnyCPU的.NET中打开大PNG会抛出内存不足异常

[英]Opening Large PNG in .NET Targeting AnyCPU Throws Out of Memory Exception

I am attempting to open a PNG image in code that is 8,733 x 12,945 pixels. 我正在尝试以8,733 x 12,945像素的代码打开PNG图像。 By my calculations, this should require 431.247 MiB (8733 * 12945 * 4) of memory to store the pixels. 根据我的计算,这需要431.247 MiB(8733 * 12945 * 4)的内存来存储像素。 However, when my build platform is AnyCPU, any attempt to open the file from C# (using new Bitmap(string filename) ) results in an OutOfMemoryException. 但是,当我的构建平台是AnyCPU时,任何从C#打开文件的尝试(使用new Bitmap(string filename) )都会导致OutOfMemoryException。 When I switch the platform to x64, the image is opened without issue. 当我将平台切换到x64时,图像打开没有问题。

Does anyone know why I would be getting such an exception trying to open an image that should require significantly less memory than the 2 GiB (2^31) threshhold? 有谁知道为什么我要尝试打开一个比2 GiB(2 ^ 31)阈值要少得多的内存的图像而得到这样的异常?

-- BEGIN EDIT -- -开始编辑-

Yes, I am aware of the concept of memory fragmentation. 是的,我知道内存碎片的概念。 I have a single WebForm, and the ONLY action that it takes is to call new Bitmap once the client selects a file from a file picker dialog. 我只有一个WebForm,并且一旦客户端从文件选择器对话框中选择了文件,它所要做的唯一操作就是调用新的位图。 My expectation is that the app does the following: 我的期望是该应用程序执行以下操作:

1) Allocates enough memory for a Windows Form (give it 20kB to be safe) 2) The user selects a file, so the app opens a stream (probably 8kB buffer) and reads the header information (first couple hundred bytes). 1)为Windows窗体分配足够的内存(为了安全起见,将其分配给20kB)2)用户选择一个文件,因此该应用打开了一个流(可能为8kB缓冲区)并读取了标头信息(前几百个字节)。 3) The header indicates the image size and pixel format, so the constructor then allocates a buffer large enough to fit the pixels (450 MB). 3)标头指示图像大小和像素格式,因此构造函数将分配一个足以容纳像素的缓冲区(450 MB)。

I understand that my memory is either very fragmented, OR GDI+ is trying to allocate the space in a strange way. 我知道我的内存非常零散,或者GDI +试图以一种奇怪的方式分配空间。 What I don't get is why this is happening? 我不明白的是为什么会这样? There is nothing resource-intensive in my application, so the memory should not be fragmented enough to prevent an allocation of about 20% of the addressable space. 我的应用程序中没有资源密集型的事情,因此内存的碎片不应足够分散,以防止分配约20%的可寻址空间。 What could be going on to prevent such an allocation? 有什么可能阻止这种分配? Does the bitmap constructor require more memory than I calculated? 位图构造函数是否需要比我计算的更多的内存?

You should use streams to read big files. 您应该使用流来读取大文件。 This exception is not related to amount of available physical memory. 此异常与可用物理内存量无关。 If you need more information you should read articles like this one: http://blogs.msdn.com/b/ericlippert/archive/2009/06/08/out-of-memory-does-not-refer-to-physical-memory.aspx 如果您需要更多信息,则应阅读以下文章: http : //blogs.msdn.com/b/ericlippert/archive/2009/06/08/out-of-memory-does-not-refer-to-physical -memory.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM