using system;
using system.collections.generic;
using system.text;
using system.drawing;
using system.drawing.drawing2d;
using system.drawing.imaging;
namespace chen
{
public class thumbnail
{
#region 生成缩略图
///
/// 生成缩略图
///
/// 源图路径(物理路径)
/// 缩略图路径(物理路径)
/// 缩略图宽度
/// 缩略图高度
/// 生成缩略图的方式
/// 生成缩略图的类型
public void makethumbnail(string originalimagepath, string thumbnailpath, int width, int height, string mode, out string outthumbnailpath, string thumbnailtype)
{
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;
switch (mode)
{
case hw://指定高宽缩放(可能变形)
break;
case w://指定宽,高按比例
toheight = originalimage.height * width / originalimage.width;
break;
case h://指定高,宽按比例
towidth = originalimage.width * height / originalimage.height;
break;
case cut://指定高宽裁减(不变形)
if ((double)originalimage.width / (double)originalimage.height > (double)towidth / (double)toheight)
{
oh = originalimage.height;
ow = originalimage.height * towidth / toheight;
y = 0;
x = (originalimage.width - ow) / 2;
}
else
{
ow = originalimage.width;
oh = originalimage.width * height / towidth;
x = 0;
y = (originalimage.height - oh) / 2;
}
break;
default:
break;
}
//新建一个bmp图片
image bitmap = new bitmap(towidth, toheight);
//新建一个画板
graphics g = graphics.fromimage(bitmap);
//设置高质量插值法
g.interpolationmode = interpolationmode.high;
//设置高质量,低速度呈现平滑程度
g.smoothingmode = smoothingmode.highquality;
//清空画布并以透明背景色填充
g.clear(color.transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.drawimage(originalimage, new rectangle(0, 0, towidth, toheight), new rectangle(x, y, ow, oh), graphicsunit.pixel);
try
{
//以各种格式保存缩略图
switch (thumbnailtype)
{
case ico:
bitmap.save(thumbnailpath, imageformat.icon);
break;
case jpg:
bitmap.save(thumbnailpath, imageformat.jpeg);
break;
case bmp:
bitmap.save(thumbnailpath, imageformat.bmp);
break;
case gif:
bitmap.save(thumbnailpath, imageformat.gif);
break;
default:
bitmap.save(thumbnailpath, imageformat.jpeg);
break;
}
outthumbnailpath = thumbnailpath;
}
catch (system.exception e)
{
throw e;
}
finally
{
originalimage.dispose();
bitmap.dispose();
g.dispose();
}
}
}
#endregion
}
