Attempting to load a huge image (e.g. a 9000x9000 pixel image) into a Bitmap object can create out-of-memory errors, a "Parameter is not valid" error, and no doubt other related problems.
How can I load a 9000x9000pixel image from disk, ultimately resizing it before saving back to disk, without causing a fatal error (such as out-of-memory)?
Let's assume a 32-bit environment with 2gb of ram, C# 4.0, and will be working with image formats of jpg, gif, bmp, tif, png.
I have tried the following 3 snippets, and each fail with a memory error.
Attempt 1:
using (Bitmap srcImg = new Bitmap(@"C:\9000x9000.jpg"))
{
// boom
}
Attempt 2:
using (Image srcImg = Image.FromFile(@"C:\9000x9000.jpg"))
{
// kapow
}
Attempt 3:
using (FileStream fs = new FileStream(@"C:\9000x9000.jpg", FileMode.Open, FileAccess.Read))
{
using (Image srcImg = Image.FromStream(fs))
{
// kelly clarkson
}
}
My thought for a possible solution is to load the image file directly into an array (so you don't have the huge overhead of a Bitmap object), somehow resize it smaller using that array (probably need to code for different image format headers?), before finally converting to a Bitmap object of manageable size.
Thoughts or possible solutions?