缩略图生成代码(ThumbnailGenerator)

// 代码来自 http://blog.csdn.net/ojekleen/archive/2008/08/01/2754255.aspx // 有修改public class ThumbnailGenerator { /// /// 从源图像生成缩略图 /// /// /// /// /// public Image GetThumbnail(Image source, int thumbWidth, int thumbHeight) { //原图宽度和高度 int width = source.Width; int height = source.Height; int smallWidth; int smallHeight; //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽和 原图的高/缩略图的高) if (((decimal)width) / height <= ((decimal)thumbWidth) / thumbHeight) { smallWidth = thumbWidth; smallHeight = thumbWidth * height / width; } else { smallWidth = thumbHeight * width / height; smallHeight = thumbHeight; }//新建一个图板,以最小等比例压缩大小绘制原图 using (Image tempBitmap = new Bitmap(smallWidth, smallHeight)) { //绘制中间图 using (Graphics g = Graphics.FromImage(tempBitmap)) { //高清,平滑 g.InterpolationMode = InterpolationMode.High; g.SmoothingMode = SmoothingMode.HighQuality; g.Clear(Color.Black); g.DrawImage(source, new Rectangle(0, 0, smallWidth, smallHeight), new Rectangle(0, 0, width, height), GraphicsUnit.Pixel); }//新建一个图板,以缩略图大小绘制中间图 Image result = new Bitmap(thumbWidth, thumbHeight); //绘制缩略图 using (Graphics g = Graphics.FromImage(result)) { //高清,平滑 g.InterpolationMode = InterpolationMode.High; g.SmoothingMode = SmoothingMode.HighQuality; g.Clear(Color.Black); int lwidth = (smallWidth - thumbWidth) / 2; int bheight = (smallHeight - thumbHeight) / 2; g.DrawImage(tempBitmap, new Rectangle(0, 0, thumbWidth, thumbHeight), lwidth, bheight, thumbWidth, thumbHeight, GraphicsUnit.Pixel); } return result; }}/// /// 给定图片文件名,生成缩略图,并保存为文件。 /// /// 【缩略图生成代码(ThumbnailGenerator)】 /// /// /// public void GenerateThumbnail(string sourcePath, string destPath, int thumbWidth, int thumbHeight) { if (!File.Exists(sourcePath)) { throw new FileNotFoundException("sourcePath 指定的文件不存在。" + Environment.NewLine + sourcePath); }if (File.Exists(destPath)) { throw new Exception("destPath 指定的文件已存在。" + Environment.NewLine + destPath); }//原图加载 using (Image sourceImage = Image.FromFile(sourcePath)) { using (Image thumb = GetThumbnail(sourceImage, thumbWidth, thumbHeight)) { thumb.Save(destPath, ImageFormat.Jpeg); } } }}

转载于:https://www.cnblogs.com/illusion/archive/2011/08/16/2140103.html

    推荐阅读