保存图像会抛出OutOfMemory异常

时间:2014-11-28 14:11:13

标签: c# image memory

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

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 (图像,350)返回一个图像,它没有崩溃。但是在Save()方法它崩溃,说我没有记忆。重要的是要注意我执行相同的方法大约100次,对于很多图像我做错了什么?

1 个答案:

答案 0 :(得分:0)

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

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