C# Thumbnail Image generation for large images getting Out Of Memory exception

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Please find the following code to generate a thumbnail version of an image:

<div style="color:black; background-color:white
<pre><span style="color:blue public <span style="color:blue class ThumbnailGenerator
{
<span style="color:blue public <span style="color:blue void GenerateThumnail(<span style="color:blue int thumbWidth, <span style="color:blue string src, <span style="color:blue string dest)
{

<span style="color:blue try
{
<span style="color:blue using (System.Drawing.Image image = System.Drawing.Image.FromFile(src))
{
<span style="color:blue int srcWidth = image.Width;
<span style="color:blue int srcHeight = image.Height;
<span style="color:blue int thumbHeight = Convert.ToInt32(Math.Round(Convert.ToDouble<br/> (Convert.ToDouble(srcHeight) / Convert.ToDouble(srcWidth) * thumbWidth), <br/> MidpointRounding.ToEven));

<span style="color:blue using (Bitmap bmp = <span style="color:blue new Bitmap(thumbWidth, thumbHeight))
{
<span style="color:blue using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp))
{
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

System.Drawing.Rectangle rectDestination = <span style="color:blue new System.Drawing.Rectangle(0, 0, thumbWidth, <br/> thumbHeight);
gr.DrawImage(image, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);

bmp.Save(dest, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
}
<span style="color:blue catch
{
<span style="color:blue throw;
}
}
}
[/code]


<br/>
This code fails with an Out Of Memory exception when used with a very large image e.g. 10 mb from a web application. The failure also seems to be tied up with machine configuration as it is happening for some machines with poor config and in some machines with
better configuration, it succeeds. I am sure it is tied somehow to the memory utilization demand for the code when handling a large image, but I am not sure that it is really only the restrictive size of the image which causes the process to crash. Is there
any better and more memory optimized way to load, process and redraw the thumbnail image? Also, it will be helpful if someone can point out the exact memory intensive steps in the above code.
<
Soumya<br/>

View the full article
 
Back
Top