Reset Image Size 2
你会留意到Insus.NET在前一次的写了Reset Image Size的功能http://www.cnblogs.com/insus/articles/1909037.html,这个功能是在图片显示时去做图片缩略,有网友向Insus.NET提及,这样做有点不好,就是每run一次,系统就要缩略生成一次,这样会有损性能,希望能改善一下。为了改善性能,哪只有在图片上传时或在图片管理时,实现一个功能保存一份缩略图在目录中。
下面是代码(部分),请参考:
View Code
System.Drawing.Image imgOriginal = System.Drawing.Image.FromFile(originalImagePath);
//获取原图片的的宽度与高度
int originalWidth = imgOriginal.Width;
int originalHeight = imgOriginal.Height;
//定义缩略图片宽度和高度
int thumbnailWidth, thumbnailHeight;
//如果原图片的宽度与高度都小于缩略图片尺寸
if (originalWidth < thumbnailSize && originalHeight < thumbnailSize)
{
thumbnailWidth = originalWidth; //宽度等于原宽度
thumbnailHeight = originalHeight;//高度等于原高度
}
//如果原图片宽度大于原图片的高度
else if (originalWidth > originalHeight)
{
thumbnailWidth = thumbnailSize; //宽度等于缩略图片尺寸
thumbnailHeight = originalHeight * thumbnailSize / originalWidth; //高度做相应比例缩小
}
//如果原图片高度大于原图片的宽度
else
{
thumbnailWidth = originalWidth * thumbnailSize / originalHeight; //宽度做相应比例缩小
thumbnailHeight = thumbnailSize; //高度等于缩略图片尺寸
}
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(thumbnailWidth, thumbnailHeight);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
//设置缩略图片质量
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.DrawImage(imgOriginal, 0, 0, thumbnailWidth, thumbnailHeight);
// 保存缩略图片
bitmap.Save(imageSavePath);
//获取原图片的的宽度与高度
int originalWidth = imgOriginal.Width;
int originalHeight = imgOriginal.Height;
//定义缩略图片宽度和高度
int thumbnailWidth, thumbnailHeight;
//如果原图片的宽度与高度都小于缩略图片尺寸
if (originalWidth < thumbnailSize && originalHeight < thumbnailSize)
{
thumbnailWidth = originalWidth; //宽度等于原宽度
thumbnailHeight = originalHeight;//高度等于原高度
}
//如果原图片宽度大于原图片的高度
else if (originalWidth > originalHeight)
{
thumbnailWidth = thumbnailSize; //宽度等于缩略图片尺寸
thumbnailHeight = originalHeight * thumbnailSize / originalWidth; //高度做相应比例缩小
}
//如果原图片高度大于原图片的宽度
else
{
thumbnailWidth = originalWidth * thumbnailSize / originalHeight; //宽度做相应比例缩小
thumbnailHeight = thumbnailSize; //高度等于缩略图片尺寸
}
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(thumbnailWidth, thumbnailHeight);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
//设置缩略图片质量
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.DrawImage(imgOriginal, 0, 0, thumbnailWidth, thumbnailHeight);
// 保存缩略图片
bitmap.Save(imageSavePath);