2014-06-13 64 views
-1

这是我转换图像的代码,所有功能/方法都正常工作。转换图像时出现内存不足异常

int height=0,width = 0; 
     ImageFormat i; 
     foreach (string pic in files) 
     { 
      Image temp = Image.FromFile(pic); 
      if (whatisformat() != null) 
       i = whatisformat(); 
      else 
       i = GetImageFormat(temp); 
      if (sizeselected()!=-1) 
      { 
       height = sizeselected(); 
       width = getwidth(height); 
      } 
      else 
      { 
       width = temp.Width; 
       height = temp.Height; 
      } 
      Formatresizesave(temp, i, height, width, destination,Path.GetFileName(pic)); 
      progressBar1.Value++; 
     } 
    } 

我一直在得到一个内存不足的例外,虽然我有大量的RAM /内存在我的电脑上。 我的固态硬盘和32GB内存已超过60 GB,但仍然遇到内存不足异常。什么可能导致问题?在我做的测试中,我只转换了小于6MB的图片。 顺便说一下,Files是一个包含文件夹中所有文件路径的列表。 而目标是在别处声明的全局变量。

+4

你已经尝试过在图像上完成后调用'Dispose'?顺便说一句,你可以得到'OutOfMemoryException'而不会接近实际的内存限制。 – BradleyDotNET

+0

不,我没有,我不熟悉Dispose方法..对不起,如果我是“Noob”。我如何调用方法,我应该在哪里调用它? – Bodokh

+1

这实际上很可能是一个无效的参数,而不是真正的OOM。 GDI +(它是System.Drawing的基础)喜欢这样做。例如,如果您的宽度/高度参数为负值,如果目标/源矩形位于图像之外,...所有这些都会导致OOM异常。 – CodesInChaos

回答

4

确保您构建的是x64,而不是x86。如果你为x86构建,你的进程将被限制在2GB内存,而你拥有32GB的物理内存并不重要。您还应该使用using块的每个图像Dispose

int height=0,width = 0; 
    ImageFormat i; 
    foreach (string pic in files) 
    { 
     using (Image temp = Image.FromFile(pic)) 
     { 
      if (whatisformat() != null) 
       i = whatisformat(); 
      else 
       i = GetImageFormat(temp); 
      if (sizeselected()!=-1) 
      { 
       height = sizeselected(); 
       width = getwidth(height); 
      } 
      else 
      { 
       width = temp.Width; 
       height = temp.Height; 
      } 
      Formatresizesave(temp, i, height, width, destination,Path.GetFileName(pic)); 
      progressBar1.Value++; 
     } 
    } 
} 
+3

对不起,挑剔,但内存真的不是这里的重点。 2 GB的限制在地址空间上。不管是由RAM还是磁盘支持,都是重点。 –

+0

@BrianRasmussen硬盘驱动器的虚拟内存回退并不可靠。在大多数系统中,如果您为x86构建然后尝试分配3GB的对象,程序将崩溃,因为分配开始失败,即使存在可用的8GB RAM。 –

+2

@TimothyShields这是因为每32位进程只有2-3 GB的用户模式虚拟地址空间。这些程序因为耗尽地址空间而崩溃,而不是内存不足。这是布赖恩试图告诉你的。 – CodesInChaos