简体   繁体   English

如何从C#中的对象重用相同的内存? (特别是位图)

[英]How do you reuse the same memory from an object in C#? (Bitmap in particular)

I'm writing a simple image resizing program. 我正在编写一个简单的图像大小调整程序。 By dragging multiple files onto the .exe, it will go through and resize each file. 通过将多个文件拖到.exe上,它将遍历并调整每个文件的大小。 It works up to a certain point where an OOM (out of memory) exception is being thrown. 它可以在某些情况下抛出OOM(内存不足)异常。 I've tried calling Dispose on the bitmap and setting it to Null, but neither seems to do anything. 我尝试在位图上调用Dispose并将其设置为Null,但似乎都没有任何作用。

Bitmap current_image;
for (int i = 0; i < imagesfilepath.Count; ++i)
        {
            // Load the image. 
            if ( current_image != Null )
            {
                current_image.Dispose();
                current_image = Null;
            }
            current_image = (Bitmap)Image.FromFile(imagesfilepath[i], true);

            // Resize it.
            // Save it.
        }

The exception is generally thrown after 1.5 GB has been used. 通常在使用1.5 GB后会引发异常。 I can get around this issue by limiting the amount of images a user can resize at one time, but shouldn't I be able to just allocate memory for 1 Bitmap, and reuse it every iteration? 我可以通过限制用户一次可以调整大小的图像数量来解决此问题,但是我不应该只为1位图分配内存,并在每次迭代中重用它吗?

Image.FromFile() throws OutOfMemoryException when the file is not a valid image: 当文件不是有效的图像时,Image.FromFile()抛出OutOfMemoryException:

Exception Condition OutOfMemoryException 异常条件OutOfMemoryException
The file does not have a valid image format. 该文件没有有效的图像格式。 -or- GDI+ does not support the pixel format of the file. -或者-GDI +不支持文件的像素格式。

Yes, this makes no sense and is confusing, but it is what it is. 是的,这没有任何意义并且令人困惑,但这就是事实。

MSDN: Image.FromFile MSDN: Image.FromFile

The out of memory is caused by memory segmentation, lack of a contiguous memory block of required size. 内存不足是由内存分段,缺少所需大小的连续内存块引起的。 you should rather use the same buffer to avoid it. 您应该使用相同的缓冲区来避免它。

As long as you dispose of the images you should not receive the OutOfMemoryException. 只要处理图像,就不会收到OutOfMemoryException。 Tested with the following snippet where disposing allowed the program to finish successfully while not disposing caused the exception. 使用以下代码片段进行了测试,在该代码片段中,配置允许程序成功完成而没有配置,则导致异常。

var path = @"C:\Users\mdearing\Desktop\Untitled.bmp";
for (var i = 0; i < 1000; i++)
{
    var image = Bitmap.FromFile(path);
    //image.Dispose(); //commenting this line out causes the OOM Exception
}

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

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