While working different applications, you will need to preserve aspect ratio of images while creating a high quality thumbnail. There are plenty of examples of this on various sites, so I figure one more will not hurt.
[TestFixture]
public class ImageResizingTestFixture
{
[Test]
public void TestResizeImageFromMemoryStream()
{
Graphics g;
// create a source bitmap image
Bitmap source = new Bitmap(500, 500);
g = Graphics.FromImage(source);
// draw a background color
g.FillRectangle(new SolidBrush(Color.Red), 0, 0, 500, 500);
g.DrawEllipse(new Pen(Color.White), 0, 0, 50, 50);
// call private thumb
Bitmap thumbnail = CreateThumbnail(source, 177, 103);
// save image as stream
MemoryStream sourceStream = new MemoryStream();
source.Save(sourceStream, ImageFormat.Jpeg);
sourceStream.Position = 0;
}
private static Bitmap CreateThumbnail(Image source, int width, int height)
{
// get the new size
Size size = GetResizeDimensions(source.Width, source.Height, width, height);
// create thumbnail holder
Bitmap thumb = new Bitmap(width, height);
Graphics g = Graphics.FromImage(thumb);
// set graphic options
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// draw the source onto the thumbnail
g.DrawImage(source, 0, 0, size.Width, size.Height);
g.Dispose();
return thumb;
}
public static Size GetResizeDimensions(int currentWidth, int currentHeight, int desiredWidth, int desiredHeight)
{
double liChange;
int newHeight;
int newWidth;
if (currentHeight == currentWidth)
{
// image is square...
// we can use either height or width to resize....
// use height
liChange = 1.0 * desiredHeight / currentHeight;
newHeight = (int) (currentHeight * liChange);
newWidth = (int)(currentWidth * liChange);
}
else if (currentHeight < currentWidth)
{
// image is landscape...use width to resize
liChange = 1.0 * desiredWidth / currentWidth;
newHeight = (int) (currentHeight * liChange);
newWidth = desiredWidth;
}
else
{
// image is portrait...
liChange = 1.0 * desiredHeight/currentHeight;
newHeight = desiredHeight;
newWidth = (int)(currentWidth * liChange);
}
if (currentHeight <= desiredHeight & currentWidth <= desiredWidth)
{
newHeight = currentHeight;
newWidth = currentWidth;
}
return new Size(newWidth, newHeight);
}
}