C#生成缩略图
2015-04-24 11:40 糯米粥 阅读(829) 评论(0) 编辑 收藏 举报很多时候。用户上传一张图片。需要生成不同尺寸的缩略图,当然。缩略图不能大于当前上传的图像。否则分辨率变了。头像就不清晰了
下面附上代码。
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 }
运行项目后。成功的生成了缩略图
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?