/// <summary> /// /// </summary> /// <param name="sFile">原图片</param> /// <param name="dFile">压缩后保存位置</param> /// <param name="dHeight">高度</param> /// <param name="dWidth">宽度</param> /// <param name="flag">压缩质量 1-100</param> public static bool GetPicThumbnail(string sFile, string dFile, int flag) { Bitmap original = (Bitmap)Image.FromFile(sFile); ImageFormat tFormat = original.RawFormat; //获取图片宽度 int sourceWidth = original.Width; //获取图片高度 int sourceHeight = original.Height; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; //计算宽度的缩放比例 nPercentW = ((float)300 / (float)sourceWidth); //计算高度的缩放比例 nPercentH = ((float)3000 / (float)sourceHeight); if (nPercentH < nPercentW) nPercent = nPercentH; else nPercent = nPercentW; //期望的宽度 int destWidth = (int)(sourceWidth * nPercent); //期望的高度 int destHeight = (int)(sourceHeight * nPercent); Bitmap bmp = new Bitmap(original, new Size(destWidth, destHeight*2)); //bmp.SetResolution(original.HorizontalResolution, original.VerticalResolution); using (var g = Graphics.FromImage(bmp)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(original, 0, 0, destWidth, destHeight*2); //g.Clear(Color.White); //g.DrawImageUnscaled(original, 0, 0); } //保存图片时,压缩图片 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-10 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { //图片背景透明 ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { bmp.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径 } else { bmp.Save(dFile, tFormat); } return true; } catch(Exception ex) { return false; } finally { original.Dispose(); bmp.Dispose(); } }
分类:
.NET
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义