I'm working on an application where I have the need to display properly scaled images within an area of limited size. I considered two different approaches for this problem. First, I can use the framework's image class to resize the image on disk when the user initially downloads it, but since I also need to display at a larger size I would need to keep two copies. The primary benefit to this approach, as I see it, is that it would reduce the size of the image on disk, therefore reducing the amount of data downloaded by the user. The second approach, and the one I'll demonstrate here, involves simply setting the size attributes of an img tag to display the properly scaled image within the specified area.
/// <summary>
/// Creates the markup to display an image scaled to a specified size.
/// </summary>
/// <param name="maxWidth">A <see cref="T:System.Int"></see> indicating the maximum available width.</param>
/// <param name="maxHeight">A <see cref="T:System.Int"></see> indicating the maximum available height.</param>
/// <param name="relativeImagePath">The relative path to the image.</param>
/// <returns></returns>
public static string GetThumbnailMarkup(int maxWidth, int maxHeight, string relativeImagePath)
{
if (string.IsNullOrEmpty(relativeImagePath))
throw new ArgumentNullException("relativeImagePath");
System.Drawing.Image currentImg = null;
string fullPath = HttpContext.Current.Server.MapPath(relativeImagePath);
using (currentImg = System.Drawing.Image.FromFile(fullPath))
{
int sourceWidth = currentImg.Width;
int sourceHeight = currentImg.Height;
float percent;
float heightPercentage;
float widthPercentage;
widthPercentage = ((float)maxWidth / (float)sourceWidth);
heightPercentage = ((float)maxHeight / (float)sourceHeight);
if (heightPercentage < widthPercentage)
{
percent = heightPercentage;
}
else
{
percent = widthPercentage;
}
int scaledWidth = (int)(sourceWidth * percent);
int scaledHeight = (int)(sourceHeight * percent);
return @"<img src=""" + relativeImagePath + @""" height=""" + scaledHeight.ToString() + @""" width=""" + scaledWidth.ToString() + @""">";
}
return string.Empty;
}
I'm sure there are better ways to do this, so if you know of one please feel free to share.