C#生成高质量缩略图

上传一张很大的图片,有时候需要以缩略图显示(比如上传头像),强制控制大图片的宽和高随然可以,

但这样非常浪费资源.所以我建议大家在图片量比较大,而且需要缩略图显示的,最好是另外生成缩略图.

我这里写了一段生成高质量缩略图的方法,供大家参考,可以直接使用.

private void ThumbnailImage(string oldImagePath, string newImagePath, int newWidth, int newHeight)
{
string originalFilename = oldImagePath;
//生成的高质量图片名称
string strGoodFile = newImagePath;

//从文件取得图片对象
System.Drawing.Image image = System.Drawing.Image.FromFile(originalFilename);

//取得图片大小
System.Drawing.Size size = new Size(newWidth, newHeight);

//新建一个bmp图片
System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height);

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

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

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

//清空一下画布
g.Clear(Color.Transparent);

//在指定位置画图
g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.GraphicsUnit.Pixel);
image.Dispose();

//保存高清晰度的缩略图
bitmap.Save(strGoodFile, GetFormat(strGoodFile));

//释放
image.Dispose();
g.Dispose();

}


/// <summary>
/// 得到图片格式
/// </summary>
/// <param name="name">文件名称</param>
/// <returns></returns>

private ImageFormat GetFormat(string name)
{
string ext = name.Substring(name.LastIndexOf(".") + 1);
switch (ext.ToLower())
{
case "jpg":
case "jpeg":
return ImageFormat.Jpeg;
case "bmp":
return ImageFormat.Bmp;
case "png":
return ImageFormat.Png;
case "gif":
return ImageFormat.Gif;
default:
return ImageFormat.Jpeg;
}

}
posted on 2008-12-09 13:39 发布:水寒冰 阅读(702) 评论(2) 收藏 所属分类: ASP.NET(C#)
tb
『2010-03-12 02:16』

不设置压缩质量,存出来的JPG缩略图画质高不起的.

水寒冰
『2010-03-14 17:09』

@tb
其实生成缩略图,设高质量和不设高质量的区别非常小,如果是将小图拉伸成大图,那区别就很明显了,特别是色彩丰富的图。
InterpolationMode.NearestNeighbor可以使图片放大以后显示真实的象素,类似于马赛克效果

  • 评论
  • 点击刷新
  • [使用Ctrl+Enter键可以直接提交]

表情图标

[smile][confused][cool][cry][eek][angry][wink][sweat][lol][stun][razz][redface][rolleyes][sad][yes][no][heart][star][music][idea]
Advertise
Category
Time Counter

离十一还有

Recent Article
Statistics
Recent Comments
Archive
Links
Support
《良机》 鲜果阅读器订阅图标
 
TOP