asp.net生成高质量缩略图通用函数
1

/**//// <summary>2
/// 生成缩略图3
/// </summary>4
/// <param name="originalImagePath">源图路径(物理路径)</param>5
/// <param name="thumbnailPath">缩略图路径(物理路径)</param>6
/// <param name="width">缩略图宽度</param>7
/// <param name="height">缩略图高度</param>8
/// <param name="mode">生成缩略图的方式</param> 9
public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)10

{11
Image originalImage = Image.FromFile(originalImagePath);12
13
int towidth = width;14
int toheight = height;15
16
int x = 0;17
int y = 0;18
int ow = originalImage.Width;19
int oh = originalImage.Height; 20

21
switch (mode)22

{ 23
case "HW"://指定高宽缩放(可能变形) 24
break;25
case "W"://指定宽,高按比例 26
toheight = originalImage.Height * width/originalImage.Width;27
break;28
case "H"://指定高,宽按比例29
towidth = originalImage.Width * height/originalImage.Height; 30
break; 31
case "Cut"://指定高宽裁减(不变形) 32
if((double)originalImage.Width/(double)originalImage.Height > (double)towidth/(double)toheight)33

{34
oh = originalImage.Height;35
ow = originalImage.Height*towidth/toheight;36
y = 0;37
x = (originalImage.Width - ow)/2;38
}39
else40

{41
ow = originalImage.Width;42
oh = originalImage.Width*height/towidth;43
x = 0;44
y = (originalImage.Height - oh)/2;45
}46
break; 47
default :48
break;49
} 50
51
//新建一个bmp图片52
Image bitmap = new System.Drawing.Bitmap(towidth,toheight);53

54
//新建一个画板55
Graphics g = System.Drawing.Graphics.FromImage(bitmap);56

57
//设置高质量插值法58
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;59

60
//设置高质量,低速度呈现平滑程度61
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;62

63
//清空画布并以透明背景色填充64
g.Clear(Color.Transparent); 65

66
//在指定位置并且按指定大小绘制原图片的指定部分67
g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), 68
new Rectangle(x, y, ow,oh),69
GraphicsUnit.Pixel);70

71
try72

{ 73
//以jpg格式保存缩略图74
bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);75
}76
catch(System.Exception e)77

{78
throw e;79
}80
finally81

{82
originalImage.Dispose();83
bitmap.Dispose(); 84
g.Dispose();85
}86
}87


浙公网安备 33010602011771号