AffineTool.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //############################################################
  2. // https://github.com/yuzhengyang
  3. // author:yuzhengyang
  4. //############################################################
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Drawing;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace Y.Utils.IOUtils.ImageUtils
  12. {
  13. public class AffineTool
  14. {
  15. /// <summary>
  16. /// 逆时针旋转图像
  17. /// </summary>
  18. /// <param name="originalImagePath">原始图像路径</param>
  19. /// <param name="saveImagePath">保存图像的路径</param>
  20. /// <param name = "angle" > 旋转角度[0, 360](前台给的) </ param >
  21. /// <returns></returns>
  22. public static bool RotateImg(string originalImagePath, string saveImagePath, int angle)
  23. {
  24. Image originalImage = Image.FromFile(originalImagePath);
  25. angle = angle % 360;
  26. //弧度转换
  27. double radian = angle * Math.PI / 180.0;
  28. double cos = Math.Cos(radian);
  29. double sin = Math.Sin(radian);
  30. //原图的宽和高
  31. int w = originalImage.Width;
  32. int h = originalImage.Height;
  33. int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
  34. int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
  35. //目标位图
  36. Bitmap saveImage = new Bitmap(W, H);
  37. Graphics g = Graphics.FromImage(saveImage);
  38. g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
  39. g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  40. //计算偏移量
  41. Point Offset = new Point((W - w) / 2, (H - h) / 2);
  42. //构造图像显示区域:让图像的中心与窗口的中心点一致
  43. Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
  44. Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
  45. g.TranslateTransform(center.X, center.Y);
  46. g.RotateTransform(360 - angle);
  47. //恢复图像在水平和垂直方向的平移
  48. g.TranslateTransform(-center.X, -center.Y);
  49. g.DrawImage(originalImage, rect);
  50. //重至绘图的所有变换
  51. g.ResetTransform();
  52. g.Save();
  53. //保存旋转后的图片
  54. originalImage.Dispose();
  55. try
  56. {
  57. saveImage.Save(saveImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
  58. return true;
  59. }
  60. catch (Exception e) { return false; }
  61. finally
  62. {
  63. originalImage.Dispose();
  64. saveImage.Dispose();
  65. g.Dispose();
  66. }
  67. }
  68. }
  69. }