【问题标题】:Saving image throws OutOfMemory exception保存图像会引发 OutOfMemory 异常
【发布时间】:2015-01-27 05:18:42
【问题描述】:

这是我下载和保存图片的代码:

using (var webClient = new WebClient())
        {
            byte[] data = webClient.DownloadData(string.Format("http://muserver.com/{0}", url.TrimStart('/')));

            var memory = new MemoryStream(data);
            var image = System.Drawing.Image.FromStream(memory);

            image.Save(pathOriginal, ImageFormat.Png);
            ResizeImageFixedWidth(image, 350).Save(pathDetails, ImageFormat.Png);
        }

public static System.Drawing.Image ResizeImageFixedWidth(System.Drawing.Image imgToResize, int width)
    {
        int sourceWidth = imgToResize.Width;

        if (sourceWidth > width)
        {
            int sourceHeight = imgToResize.Height;

            float nPercent = ((float)width / (float)sourceWidth);

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return (System.Drawing.Image)b;
        }
        else
        {
            return imgToResize;
        }
    }

ResizeImageFixedWidth(0 是我用来调整图像大小但保存纵横比的方法。我想做的是:将相同的图像保存在 2 个文件夹中,一次以原始大小保存,一次以 350 的宽度保存。ResizeImageFixedWidth (image, 350) 返回一个图像,它没有崩溃。但是在 Save() 方法上它崩溃了,说我内存不足。可能需要注意的是,对于很多图像,我执行了大约 100 次相同的方法. 我做错了什么?

【问题讨论】:

  • 可能不是问题所在。但是你应该处理你的流、图像、位图和图形。查看using 声明
  • 可能需要注意的是,我对很多图像执行了大约 100 次相同的方法。我做错了什么? 你没有处理所有这些 inages。保存后添加image.Dispose();!! (GDI 的东西是 GC 的!)
  • 尝试关闭并释放内存流或使用 using 并尝试 GC.Collect

标签: c# image memory


【解决方案1】:

将您的语句包装到 using 语句中,以便自动关闭和处理流。

using (MemoryStream stream = new MemoryStream(data)
{
    using(Image myImage = Image.FromStream(stream))
    {
        //do stuff
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 2011-09-03
    • 2013-01-09
    • 1970-01-01
    相关资源
    最近更新 更多