简体   繁体   中英

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?

Wrap your statements into a using statement so that the streams are automatically closed and disposed.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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