C#缩放和裁剪图片

时间:2025-03-21 23:05:43

在GDI+中,缩放和剪裁可以看作同一个操作,无非就是原始区域的选择不同罢了。空口无凭,先看具体算法可能更好理解。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Drawing;
  5. using System.Drawing.Drawing2D;
  6. using System.Drawing.Imaging;
  7. namespace Project
  8. {
  9. class ImageOperation
  10. {
  11. /// <summary>
  12. ///  Resize图片
  13. /// </summary>
  14. /// <param name="bmp">原始Bitmap </param>
  15. /// <param name="newW">新的宽度</param>
  16. /// <param name="newH">新的高度</param>
  17. /// <param name="Mode">保留着,暂时未用</param>
  18. /// <returns>处理以后的图片</returns>
  19. public static Bitmap ResizeImage(Bitmap bmp, int newW, int newH, int Mode)
  20. {
  21. try
  22. {
  23. Bitmap b = new Bitmap(newW, newH);
  24. Graphics g = Graphics.FromImage(b);
  25. // 插值算法的质量
  26. g.InterpolationMode = InterpolationMode.HighQualityBicubic;
  27. g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
  28. g.Dispose();
  29. return b;
  30. }
  31. catch
  32. {
  33. return null;
  34. }
  35. }
  36. /// <summary>
  37. /// 剪裁 -- 用GDI+
  38. /// </summary>
  39. /// <param name="b">原始Bitmap</param>
  40. /// <param name="StartX">开始坐标X</param>
  41. /// <param name="StartY">开始坐标Y</param>
  42. /// <param name="iWidth">宽度</param>
  43. /// <param name="iHeight">高度</param>
  44. /// <returns>剪裁后的Bitmap</returns>
  45. public static Bitmap Cut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
  46. {
  47. if (b == null)
  48. {
  49. return null;
  50. }
  51. int w = b.Width;
  52. int h = b.Height;
  53. if (StartX >= w || StartY >= h)
  54. {
  55. return null;
  56. }
  57. if (StartX + iWidth > w)
  58. {
  59. iWidth = w - StartX;
  60. }
  61. if (StartY + iHeight > h)
  62. {
  63. iHeight = h - StartY;
  64. }
  65. try
  66. {
  67. Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
  68. Graphics g = Graphics.FromImage(bmpOut);
  69. g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
  70. g.Dispose();
  71. return bmpOut;
  72. }
  73. catch
  74. {
  75. return null;
  76. }
  77. }
  78. }
  79. }

目标其实都是new Rectangle(0, 0, iWidth, iHeight),缩放算法把整个原始图都往目标区域里塞new Rectangle(0, 0, bmp.Width, bmp.Height),而剪裁只是把原始区域上等宽等高的那个区域new Rectangle(StartX, StartY, iWidth, iHeight)1:1的塞到目标区域里。