如何重用 C# 中对象的相同内存? (特别是位图)
我正在编写一个简单的图像调整大小程序。通过将多个文件拖到 .exe 上,它将遍历每个文件并调整其大小。它会工作到抛出 OOM(内存不足)异常的某个点。我尝试在位图上调用 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.
}
该异常通常在使用 1.5 GB 后抛出。我可以通过限制用户一次可以调整大小的图像数量来解决这个问题,但是我不应该只为 1 个位图分配内存,并在每次迭代时重用它吗?
I'm writing a simple image resizing program. By dragging multiple files onto the .exe, it will go through and resize each file. It works up to a certain point where an OOM (out of memory) exception is being thrown. I've tried calling Dispose on the bitmap and setting it to Null, but neither seems to do anything.
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. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当文件不是有效图像时,Image.FromFile() 会抛出 OutOfMemoryException:
是的,这毫无意义并且令人困惑,但事实就是如此。
MSDN:Image.FromFile
Image.FromFile() throws OutOfMemoryException when the file is not a valid image:
Yes, this makes no sense and is confusing, but it is what it is.
MSDN: Image.FromFile
只要您处理了图像,您就不会收到 OutOfMemoryException。使用以下代码片段进行测试,其中处置允许程序成功完成,而不处置导致异常。
As long as you dispose of the images you should not receive the OutOfMemoryException. Tested with the following snippet where disposing allowed the program to finish successfully while not disposing caused the exception.
内存不足是由内存分段、缺少所需大小的连续内存块引起的。您应该使用相同的缓冲区来避免它。
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.