从文件夹中读取图像时出现内存不足的异常

时间:2013-09-30 09:54:50

标签: c# asp.net image

我需要从文件夹中读取所有图像文件并将其保存到压缩大小的另一个文件夹。但是我的代码压缩这个图像非常好,但是在695个图像文件“内存不足异常”后它会出错。这是我的代码。大约有2000张图片

List<string> files = new List<string>();
files = Directory.GetFiles(Server.MapPath("../imgres") + "\\products\\", "*.jpg").ToList();
for (int k = 0; k < files.Count; k++)
{
  if (File.Exists(files[k].ToString()))
  {
    string SaveLocation1 = "";
    System.Drawing.Image thumbnail;
    System.Drawing.Image smallsize;
    System.Drawing.Image originalimg;

    originalimg = System.Drawing.Image.FromFile(files[k].ToString());
    thumbnail = originalimg.GetThumbnailImage(110, 110, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
    smallsize = originalimg.GetThumbnailImage(47, 47, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);

    SaveLocation1 = Server.MapPath("../imgres/products") + "\\Thumbnail\\" + Path.GetFileName(files[k].ToString());
    thumbnail.Save(SaveLocation1);
    thumbnail.Dispose();

    SaveLocation1 = Server.MapPath("../imgres/products") + "\\smallsize\\" + Path.GetFileName(files[k].ToString());
    smallsize.Save(SaveLocation1);
    smallsize.Dispose();

  }
}

2 个答案:

答案 0 :(得分:4)

问题在于,您没有像使用其他图像引用一样处置originalimg。您应该在if语句的末尾添加以下内容:

originalimg.Dispose();

我建议你使用using块,这些将帮助你更好地管理这些资源的处理,因为你不必隐式调用Dispose方法,它也会处理即使在您致电Dispose之前发生异常,也会处置,因此您可以确定它会被正确清理。

这样的事情:

if (File.Exists(files[k].ToString()))
{
    using(System.Drawing.Image originalimg = System.Drawing.Image.FromFile(files[k].ToString()))
    {
        using(System.Drawing.Image thumbnail = originalimg.GetThumbnailImage(110, 110, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
        {
            using(System.Drawing.Image smallsize = originalimg.GetThumbnailImage(47, 47, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
            {
                string SaveLocation1 = Server.MapPath("../imgres/products") + "\\Thumbnail\\" + Path.GetFileName(files[k].ToString());
                thumbnail.Save(SaveLocation1);

                SaveLocation1 = Server.MapPath("../imgres/products") + "\\smallsize\\" + Path.GetFileName(files[k].ToString());
                smallsize.Save(SaveLocation1);
            }
        }
    }
}

答案 1 :(得分:4)

我建议使用using块修改它,以避免需要调用(或忘记调用)Dispose方法:

using (Image originalimg = Image.FromFile(files[k].ToString()))
{
   using (Image thumbnail = originalimg.GetThumbnailImage(110, 110, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
   {
      thumbnail.Save(...);
   }

   using (Image smallsize = originalimg.GetThumbnailImage(47, 47, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
   {
      smallsize.Save(...);
   }
}