c# 无损高质量压缩图片代码

时间:2023-03-09 06:41:10
c# 无损高质量压缩图片代码
  1. /// <summary>
  2. /// 无损压缩图片
  3. /// </summary>
  4. /// <param name="sFile">原图片</param>
  5. /// <param name="dFile">压缩后保存位置</param>
  6. /// <param name="dHeight">高度</param>
  7. /// <param name="dWidth"></param>
  8. /// <param name="flag">压缩质量(数字越小压缩率越高) 1-100</param>
  9. /// <returns></returns>
  10. public static bool GetPicThumbnail(string sFile, string dFile, int dHeight, int dWidth, int flag)
  11. {
  12. System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile);
  13. ImageFormat tFormat = iSource.RawFormat;
  14. int sW = 0, sH = 0;
  15. //按比例缩放
  16. Size tem_size = new Size(iSource.Width, iSource.Height);
  17. if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号
  18. {
  19. if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth))
  20. {
  21. sW = dWidth;
  22. sH = (dWidth * tem_size.Height) / tem_size.Width;
  23. }
  24. else
  25. {
  26. sH = dHeight;
  27. sW = (tem_size.Width * dHeight) / tem_size.Height;
  28. }
  29. }
  30. else
  31. {
  32. sW = tem_size.Width;
  33. sH = tem_size.Height;
  34. }
  35. Bitmap ob = new Bitmap(dWidth, dHeight);
  36. Graphics g = Graphics.FromImage(ob);
  37. g.Clear(Color.WhiteSmoke);
  38. g.CompositingQuality = CompositingQuality.HighQuality;
  39. g.SmoothingMode = SmoothingMode.HighQuality;
  40. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  41. g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
  42. g.Dispose();
  43. //以下代码为保存图片时,设置压缩质量
  44. EncoderParameters ep = new EncoderParameters();
  45. long[] qy = new long[1];
  46. qy[0] = flag;//设置压缩的比例1-100
  47. EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
  48. ep.Param[0] = eParam;
  49. try
  50. {
  51. ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
  52. ImageCodecInfo jpegICIinfo = null;
  53. for (int x = 0; x < arrayICI.Length; x++)
  54. {
  55. if (arrayICI[x].FormatDescription.Equals("JPEG"))
  56. {
  57. jpegICIinfo = arrayICI[x];
  58. break;
  59. }
  60. }
  61. if (jpegICIinfo != null)
  62. {
  63. ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
  64. }
  65. else
  66. {
  67. ob.Save(dFile, tFormat);
  68. }
  69. return true;
  70. }
  71. catch
  72. {
  73. return false;
  74. }
  75. finally
  76. {
  77. iSource.Dispose();
  78. ob.Dispose();
  79. }
  80. }