views:

268

answers:

3

I have a need to resize pictures on a website I'm making for my company. The pictures must be a very specific size, and if the proportions are not correct I must be able to pad the image with a border to make it 'fit'. I'm not sure what the best way to approach this problem is. My knee-jerk was to simply add Rectangles to the image on the fly as I needed, but I'm unable to find a way to make a composite image like that. Should I just make a suitable, blank Rectangle, and superimpose my image over it? Which libraries or functions should I be most heavily looking at?

The resizing and saving all work great - that is not the issue. Adding this padding is the only problem.

+1  A: 

This article seems to cover your requirements:

CodeProject: Resizing a Photographic image with GDI+ for .NET By Joel Neubeck

Greg
I was all set to criticize this article for using the default InterpolationMode, then I noticed that he correctly sets it to HighQualityBicubic. Oh well, +1.
MusiGenesis
+1  A: 

The simplest way is to start with a Bitmap with the dimensions you need in your final image, then use Graphics.Clear to paint the desired background color, then use Graphics.DrawImage to copy your original image onto your main Bitmap, resizing it as necessary during this step and setting the InterpolationMode to HighQualityBicubic for best quality.

MusiGenesis
+2  A: 

Create a new Bitmap of the proper size, fill it with the padding color you want, and draw the original image in the center :

Bitmap newImage = new Bitmap(width, height);
using(Graphics graphics = Graphics.FromImage(newImage))
{
    graphics.Clear(paddingColor);
    int x = (newImage.Width - originalImage.Width) / 2;
    int y = (newImage.Height - originalImage.Height) / 2;
    graphics.DrawImage(originalImage, x, y);
}
Thomas Levesque
Dispose()/using() alert!
MusiGenesis
@MusiGenesis: good point... it's fixed now
Thomas Levesque