Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio
Target parameters:
float width = 1024;
float height = 768;
var brush = new SolidBrush(Color.Black);
Your original file:
var image = new Bitmap(file);
Target sizing (scale factor):
float scale = Math.Min(width / image.Width, height / image.Height);
The resize including brushing canvas first:
var bmp = new Bitmap((int)width, (int)height);
var graph = Graphics.FromImage(bmp);
// uncomment for higher quality output
//graph.InterpolationMode = InterpolationMode.High;
//graph.CompositingQuality = CompositingQuality.HighQuality;
//graph.SmoothingMode = SmoothingMode.AntiAlias;
var scaleWidth = (int)(image.Width * scale);
var scaleHeight = (int)(image.Height * scale);
graph.FillRectangle(brush, new RectangleF(0, 0, width, height));
graph.DrawImage(image, ((int)width - scaleWidth)/2, ((int)height - scaleHeight)/2, scaleWidth, scaleHeight);
And don't forget to do a bmp.Save(filename)
to save the resulting file.
The bitmap constructor has resizing built in.
Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");
http://msdn.microsoft.com/en-us/library/0wh0045z.aspx
If you want control over interpolation modes see this post.