Image resizing efficiency in C# and .NET 3.5

Posted by Matthew Nichols on Stack Overflow See other posts from Stack Overflow or by Matthew Nichols
Published on 2009-08-31T12:36:33Z Indexed on 2011/01/29 15:26 UTC
Read the original article Hit count: 162

Filed under:
|
|
|

I have written a web service to resize user uploaded images and all works correctly from a functional point of view, but it causes CPU usage to spike every time it is used. It is running on Windows Server 2008 64 bit. I have tried compiling to 32 and 64 bit and get about the same results.

The heart of the service is this function:

private Image CreateReducedImage(Image imgOrig, Size NewSize)
{
	var newBM = new Bitmap(NewSize.Width, NewSize.Height);
	using (var newGrapics = Graphics.FromImage(newBM))
	{
		newGrapics.CompositingQuality = CompositingQuality.HighSpeed;
		newGrapics.SmoothingMode = SmoothingMode.HighSpeed;
		newGrapics.InterpolationMode = InterpolationMode.HighQualityBicubic;
		newGrapics.DrawImage(imgOrig, new Rectangle(0, 0, NewSize.Width, NewSize.Height));
	}

	return newBM;
}

I put a profiler on the service and it seemed to indicate the vast majority of the time is spent in the GDI+ library itself and there is not much to be gained in my code.

Questions: Am I doing something glaringly inefficient in my code here? It seems to conform to the example I have seen.

Are there gains to be had in using libraries other than GDI+? The benchmarks I have seen seem to indicate that GDI+ does well compare to other libraries but I didn't find enough of these to be confident.

Are there gains to be had by using "unsafe code" blocks?

Please let me know if I have not included enough of the code...I am happy to put as much up as requested but don't want to be obnoxious in the post.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET