AffineTool.cs 2.7 KB

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