jpeg图片内存不足

本文关键字:内存不足 jpeg | 更新日期: 2023-09-27 18:10:11

我正在给图片添加水印。在几张图片之后,System.Drawing.Image给出了内存不足的错误。我的文件夹里有2000张照片。我也在using中处理了我的对象和using,但它仍然耗尽内存。

Using (System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(path)))
{
  using ( Bitmap bmp = new Bitmap(img.Width, img.Height))
  { 
        Graphics pic = Graphics.FromImage(bmp);
        Font font = new Font("Arial", 11);
        SolidBrush brush = new SolidBrush(Color.Orange);
        pic.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
        pic.DrawString(location, font, brush, 0f, bmp.Height - 20);
        pic.DrawString(date, font, brush, 300, bmp.Height - 20);
        System.Drawing.Image img3 = (System.Drawing.Image) bmp;
        string NewPath = path.Insert(path.IndexOf('.'), "-wm");
        img3.Save(Server.MapPath(NewPath));
        img3.Dispose();
        bmp.Dispose();
        img.Dispose();
        font.Dispose();
        pic.Dispose();
        brush.Dispose();
  }
}

这是代码,我所有的图片都是jpeg格式的

jpeg图片内存不足

在我看来你的代码看起来很好。虽然我可以想象一些情况下,你的代码可能会导致OutOfMemoryException。

当您使用图像时,LargeObjectHeap可能会起作用。因此,内存碎片可能是在运行代码时发生的问题。(详情请参阅LargeObjectHeapCompactionMode属性)

所以你可以试着使用:

GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();

我想知道这是否解决了你的问题。无论如何,如果你能提供更多关于这个话题的细节-这将是伟大的!