/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="sourceimagepath">原图片路径(相对路径)</param>
/// <param name="thumbnailimagepath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
/// <param name="thumbnailimagewidth">缩略图的宽度(高度与按源图片比例自动生成)</param>
public void tothumbnailimages(string sourceimagepath,string thumbnailimagepath,int thumbnailimagewidth)
{
string sourceimagepath = sourceimagepath;
string thumbnailimagepath = thumbnailimagepath;
int thumbnailimagewidth = thumbnailimagewidth;
string sext = sourceimagepath.substring(sourceimagepath.lastindexof(".")).tolower();
if(sourceimagepath.tostring()==system.string.empty) throw new nullreferenceexception("sourceimagepath
is null!");
if(!checkvalidext(sext))
{
throw new argumentexception("原图片文件格式不正确,支持的格式有[ "+ allowext +"
]","sourceimagepath");
}
//从 原图片 创建 image 对象
system.drawing.image image = system.drawing.image.fromfile(httpcontext.current.server.mappath
(sourceimagepath));
int num = ((thumbnailimagewidth / 4) * 3);
int width = image.width;
int height = image.height;
//计算图片的比例
if ((((double) width) / ((double) height)) >= 1.3333333333333333f)
{
num = ((height * thumbnailimagewidth) / width);
}
else
{
thumbnailimagewidth = ((width * num) / height);
}
if ((thumbnailimagewidth < 1) || (num < 1))
{
return;
}
//用指定的大小和格式初始化 bitmap 类的新实例
bitmap bitmap = new bitmap(thumbnailimagewidth, num, pixelformat.format32bppargb);
//从指定的 image 对象创建新 graphics 对象
graphics graphics = graphics.fromimage(bitmap);
//清除整个绘图面并以透明背景色填充
graphics.clear(color.transparent);
//在指定位置并且按指定大小绘制 原图片 对象
graphics.drawimage(image, new rectangle(0, 0, thumbnailimagewidth, num));
image.dispose();
try
{
//将此 原图片 以指定格式并用指定的编解码参数保存到指定文件
string savepath = (thumbnailimagepath==null?sourceimagepath:thumbnailimagepath);
saveimage(bitmap,httpcontext.current.server.mappath(savepath),getcodecinfo((string)htmimes
[sext]));
}
catch(system.exception e)
{
throw e;
}
finally
{
bitmap.dispose();
graphics.dispose();
}
}
#endregion
}
}