简体   繁体   中英

System.OutOfMemoryException when loading multiple large images from disk

I try to load images from disk (sizes of 30 to 50 MB each) in a list as follows

    var images = new List<Image>();
    foreach (var imgPath in paths)
    {
        var img = Image.FromFile(imgPath);
        images.Add(img);
    }

The problem is that after the first or second image I get a

System.OutOfMemoryException

...my guess is that the images are too large. I know that a good practice would be to process the images one by one, but I can't since I need all of them to be merged into a single one (like a collage) and I can't use thumbnails because I need to respect the original sizes.

I tried to change the maxRequestLength to "10000000" but it was useless.

Since I can't reach the image processing step I don't think that I have a problem with not disposing objects, at least not yet.

Is there a way to increase the memory available to work with, or something like that?

PS I use JPG format for images.

I don't recommend using:

Image.FromFile(path);

It's slow and will bloat your process Instead:

var fs = new FileStream(path, FileMode.Open, FileAccess.Read);
var photo = Image.FromStream(fs, true, false);

Don't forget to dispose ;-)

Basically instead of bringing all that data into memory in one go and killing your app and all your loved ones. You operate the image as if it was a stream of data.

Edit

In either case I don't recommend editing all the images at once. You'll probably get a OutOfMemoryException either way.

If possible work with two images at the time, once you're done, dispose them and move to the next set until your final image is complete.

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