简体   繁体   English

保存图像会抛出OutOfMemory异常

[英]Saving image throws OutOfMemory exception

This is my code for downloading and saving images: 这是我用于下载和保存图像的代码:

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 is a method I use for resizing the image but saving the aspect ration. WHat I want to do is this: save the same image in 2 folders, once in the original size and once with width of 350. ResizeImageFixedWidth(image, 350) returns an image, it doesnt crash. But on the Save() method it crashes, saying I am out of memory. It's probably important to note that I execute the same method about 100 times, for a lot of images. What am I doing wrong? ResizeImageFixedWidth(0是我用来调整图像大小但保存宽高比的一种方法。我想要做的是:将相同图像保存在2个文件夹中,一次保存为原始大小,一次保存为350宽度。ResizeImageFixedWidth(image, 350)返回一个图像,它不会崩溃。但是在Save()方法上,它崩溃了,说我的内存不足。需要注意的是,对于很多图像,我执行相同的方法大约100次可能很重要。我做错了吗?

Wrap your statements into a using statement so that the streams are automatically closed and disposed. 将您的语句包装到using语句中,以便自动关闭和处理流。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM