Sakset fra mit eget bibliotek:
public static class Imaging
{
/// <summary>
/// Scales a image proportions to the given maximum width.
/// </summary>
/// <param name="image"></param>
/// <param name="maxWidth">Maximum width of the thumbnail.</param>
/// <returns></returns>
public static Image ScaleHorisontal(this Image image, int maxWidth)
{
int width, height;
if(image.Width > image.Height)
{
width = maxWidth;
height = image.Height * maxWidth / image.Width;
}
else
{
width = image.Width * 400 / image.Height;
height = maxWidth;
}
using(Bitmap b = new Bitmap(width, height))
{
using(Graphics g = Graphics.FromImage((Image)b))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(image, 0, 0, width, height);
}
try
{
return (Image)b.Clone();
}
finally
{
b.Dispose();
}
}
}
}
Eksemple på brug:
string filename = "large.jpg";
string thumbnail = Path.Combine(
Path.GetTempPath(), Path.GetFileName(fileName)
);
using(Image thumbnailImage = Image.FromFile(fileName).ScaleHorisontal(400))
{
// Gemt i Systemets TEMP folder, hvorefter du kan flytte det hvorhen du har lyst.
thumbnailImage.Save(thumbnail);
}