C#生成缩略图
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="originalImagePath">原图路径</param>
/// <param name="thumbnailPath">生成缩略图的保存路径</param>
/// <param name="width">要生成的缩略图的宽</param>
/// <param name="height">要生成的缩略图的高</param>
/// <param name="fileExt">保存图片的格式</param>
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string fileExt)
{
Image originalImage = Image.FromFile(originalImagePath);
int towidth = width;
int toheight = height;
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
//新建一个bmp图片
Image bitmap = new Bitmap(towidth, toheight);
//新建一个画板
Graphics g = Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
new Rectangle(x, y, ow, oh),
GraphicsUnit.Pixel);
try
{
//以jpg格式保存缩略图
switch (fileExt)
{
case ".jpeg":
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".jpg":
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case ".png":
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
break;
case ".gif":
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif);
break;
default:
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png);
break;
}
}
catch (Exception e)
{
throw e;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
}