C#生成缩略图

很多时候。用户上传一张图片。需要生成不同尺寸的缩略图,当然。缩略图不能大于当前上传的图像。否则分辨率变了。头像就不清晰了

下面附上代码。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Drawing;
 6 using System.Drawing.Imaging;
 7 
 8 namespace ADO.net01
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             //获取图片路径
15             string y = System.AppDomain.CurrentDomain.BaseDirectory;
16             string img = y + "1.jpg";
17 
18             Bitmap r = CreateThumbnail(img, 20, 50);
19             r.Save(y + "12.jpg"); //保存缩略图
20         }
21         //Bitmap所属命名空间 system.Drawing
22 
23         /// <summary>
24         /// 
25         /// </summary>
26         /// <param name="lcFilename">需要改变大小的图片位置</param>
27         /// <param name="lnWidth">缩略图的宽度</param>
28         /// <param name="lnHeight">缩略图的高度</param>
29         /// <returns></returns>
30         public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
31         {
32             System.Drawing.Bitmap bmpOut = null;
33             try
34             {
35                 Bitmap loBMP = new Bitmap(lcFilename);
36                 ImageFormat loFormat = loBMP.RawFormat;
37 
38                 decimal lnRatio;
39                 int lnNewWidth = 0;
40                 int lnNewHeight = 0;
41 
42                 //如果图像小于缩略图直接返回原图,因为upfront
43                 if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
44                     return loBMP;
45 
46                 if (loBMP.Width > loBMP.Height)
47                 {
48                     lnRatio = (decimal)lnWidth / loBMP.Width;
49                     lnNewWidth = lnWidth;
50                     decimal lnTemp = loBMP.Height * lnRatio;
51                     lnNewHeight = (int)lnTemp;
52                 }
53                 else
54                 {
55                     lnRatio = (decimal)lnHeight / loBMP.Height;
56                     lnNewHeight = lnHeight;
57                     decimal lnTemp = loBMP.Width * lnRatio;
58                     lnNewWidth = (int)lnTemp;
59                 }
60                 bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
61                 Graphics g = Graphics.FromImage(bmpOut);
62                 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
63                 g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
64                 g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
65 
66                 loBMP.Dispose();
67             }
68             catch
69             {
70                 return null;
71             }
72 
73             return bmpOut;
74         }
75     }
76 }

运行项目后。成功的生成了缩略图

原文地址:https://www.cnblogs.com/nsky/p/4453004.html