I'm developing a single user image gallery using C# .NET for my photos and just general coding practice and i've made a control which uploads up to 5 images and resizes them to 4 different sizes. For the most part its working fine except it often throws an out of memory error when it reaches the 4th or 5th image resizing stage.
I wont post all the code but there's 5 fileupload controls on the form and the code goes through them one at a time, saves the original image to the server, extracts EXIF info, then resizes the original image 4 times - Thumb, small, medium and large and saves each one.
Large resize code, does similar thing for each size:
The images can be up to 5MB each so I expected it to take a fair amount of memory but I think I am freeing up resources properly after each resize (.Dispose()) but I suspect its doing garbage disposal too slow? If this is the case how do you force garbage collection before each resize or make the control wait for collection before moving onto the next image resize?
Is there a more efficient way to do this or increase memory limit?
Any help and suggestions appreciated!
I wont post all the code but there's 5 fileupload controls on the form and the code goes through them one at a time, saves the original image to the server, extracts EXIF info, then resizes the original image 4 times - Thumb, small, medium and large and saves each one.
Large resize code, does similar thing for each size:
Code:
.
.
Bitmap largeImg = new Bitmap((Int32)largeNewWidth, (Int32)largeNewHeight);
Graphics largeGfx = Graphics.FromImage(largeImg);
largeGfx.FillRectangle(sb, 0, 0, largeImg.Width, largeImg.Height); //sb is a white solid brush
largeGfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
largeGfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
largeGfx.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
largeGfx.DrawImage(originalimg, 0, 0, largeImg.Width, largeImg.Height);
try
{
if (!Directory.Exists(largeSavePath))
{
string strFolderToCreate = largeSavePath;
if (largeSavePath.EndsWith(@"\"))
strFolderToCreate = largeSavePath.Substring(0, (strFolderToCreate.Length - 1));
Directory.CreateDirectory(strFolderToCreate);
}
largeImg.Save(largeSavePath + "//" + FileName, originalimg.RawFormat);
Literal1.Text += "<br /><img src='Photos/Large/" + FileName + "' alt='' border='0' /><br />";
}
catch (Exception ex)
{
lblMessage.Text += " Large image not saved " + ex.Message.ToString();
}
finally
{
largeImg.Dispose();
}
.
.
sb.Dispose();
originalimg.Dispose();
Is there a more efficient way to do this or increase memory limit?
Any help and suggestions appreciated!
Last edited: