/// <summary>
/// 按照指定的高和宽生成相应的规格的图片,采用此方法生成的缩略图片不会失真
/// </summary>
/// <param name="originalImagePath">源图路径(物理路径)</param>
/// <param name="width">指定宽度</param>
/// <param name="height">指定高度</param>
/// <returns>返回新生成的图</returns>
public static Image GetReducedImage(string originalImagePath, int width, int height)
{
Image imageFrom = Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;
toheight = imageFrom.Height * width / imageFrom.Width;
// 源图宽度及高度
int imageFromWidth = imageFrom.Width;
int imageFromHeight = imageFrom.Height;
// 如果指定得高度等于或小于原图,则直接返回原图
if (imageFromWidth <= towidth)
{
return imageFrom;
}
else
{
// 生成的缩略图在上述"画布"上的位置
int X = 0;
int Y = 0;
// 创建画布
Bitmap bmp = new Bitmap(towidth, toheight, PixelFormat.Format24bppRgb);
bmp.SetResolution(96, 96);
//bmp.SetResolution(imageFrom.HorizontalResolution, imageFrom.VerticalResolution);
using (Graphics g = Graphics.FromImage(bmp))
{
// 用白色清空
g.Clear(Color.White);
// 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
// 指定高质量、低速度呈现。
g.SmoothingMode = SmoothingMode.HighQuality;
// 在指定位置并且按指定大小绘制指定的 Image 的指定部分。
g.DrawImage(imageFrom, new Rectangle(X, Y, towidth, toheight),
new Rectangle(0, 0, imageFromWidth, imageFromHeight), GraphicsUnit.Pixel);
return bmp;
}
}
}