Running out of memory when trying to add images to zip file in .net application


March 2019


27 time


I am running a web server with a mongo database. The database stores records, which include pictures stored as base64 encoded strings.

I am writing an api call that fetches several of these images from the records, builds them in .jpg images, and adds them to a zip file stored on the server.

The problem I'm running into is that the call returns with an OutOfMemory exception after only a few records, even when the total size of the images is less than 10mb, with each image being around 500kb. Here is the code I am using:

  using (ZipFile zipFile = new ZipFile())

                var i = 0;
                foreach (ResidentialData resident in foundResidents)
                    MemoryStream tempstream = new MemoryStream();

                    Image userImage1 = LoadImage(resident.AccountImage);

                    Bitmap tmp = new Bitmap(userImage1);
                    tmp.Save(tempstream, ImageFormat.Jpeg);
                    tempstream.Seek(0, SeekOrigin.Begin);
                    byte[] imageData = new byte[tempstream.Length];
                    tempstream.Read(imageData, 0, imageData.Length);
                    zipFile.AddEntry(i + " | " + resident.Initials + " " + resident.Surname + ".jpg", imageData);


Any ideas as to what might be eating up all the memory? I don't see how this is possible as the machine it is running on has 32gb of RAM.

1 answers


You need to dispose your bitmaps.

Change this:



You might want to look into using using() blocks as they allow you to define; allocate and automatically release the resource.


using (var x = new SomethingThatNeedsDisposing())
    // do something with x
} // <----- at this point .NET will call x.Dispose() for you