C#实现任意角度旋转图片(方法2)
C#实现Windows图片查看器的旋转功能:
1private const string IMAGEFILE = "FocusPoint.JPG";
2
3 private static int MyAngle = 0; //旋转角度[-360,360]
4
5
6
7 private void Page_Load(object sender, EventArgs e)
8
9 {
10
11 Image img;
12
13 FileStream fs;
14
15
16 fs = new FileStream(IMAGEFILE, FileMode.Open, FileAccess.Read);
17
18 img = Bitmap.FromStream(fs);
19
20 fs.Close();
21
22 pictureBox1.Image = img;
23
24 }
25
26
27
28 private void button1_Click(object sender, EventArgs e)
29
30 {
31
32 MyAngle = 90;
33
34 //MyAngle += 90;
35
36 //if (MyAngle > 360) MyAngle = 90;
37
38 pictureBox1.Image = RotateImg(GetSourceImg(IMAGEFILE), MyAngle);
39
40 }
41
42
43 private void button2_Click(object sender, EventArgs e)
44
45 {
46
47 MyAngle = -90;
48
49 //MyAngle += -90;
50
51 //if (MyAngle < -360) MyAngle = -90;
52
53 //pictureBox1.Image = RotateImg(Bitmap.FromFile(IMAGEFILE), MyAngle);
54
55 pictureBox1.Image = RotateImg(IMAGEFILE, MyAngle);
56
57 }
58
59
60 #region 图片旋转函数
61
62
63 /// <summary>
64
65 /// 以逆时针为方向对图像进行旋转
66
67 /// </summary>
68
69 /// <param name="b">位图流</param>
70
71 /// <param name="angle">旋转角度[0,360](前台给的)</param>
72
73 /// <returns></returns>
74
75 public Image RotateImg(Image b, int angle)
76
77 {
78
79 angle = angle % 360;
80
81
82 //弧度转换
83
84 double radian = angle * Math.PI / 180.0;
85
86 double cos = Math.Cos(radian);
87
88 double sin = Math.Sin(radian);
89
90
91 //原图的宽和高
92
93 int w = b.Width;
94
95 int h = b.Height;
96
97 int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
98
99 int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
100
101
102 //目标位图
103
104 Bitmap dsImage = new Bitmap(W, H);
105
106 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
107
108 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
109
110 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
111
112
113 //计算偏移量
114
115 Point Offset = new Point((W - w) / 2, (H - h) / 2);
116
117
118 //构造图像显示区域:让图像的中心与窗口的中心点一致
119
120 Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
121
122 Point center = new Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
123
124
125 g.TranslateTransform(center.X, center.Y);
126
127 g.RotateTransform(360 - angle);
128
129
130 //恢复图像在水平和垂直方向的平移
131
132 g.TranslateTransform(-center.X, -center.Y);
133
134 g.DrawImage(b, rect);
135
136
137 //重至绘图的所有变换
138
139 g.ResetTransform();
140
141
142 g.Save();
143
144 g.Dispose();
145
146 //保存旋转后的图片
147
148 b.Dispose();
149
150 dsImage.Save("FocusPoint.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
151
152 return dsImage;
153
154 }
155
156
157 public Image RotateImg(string filename, int angle)
158
159 {
160
161 return RotateImg(GetSourceImg(filename), angle);
162
163 }
164
165
166 public Image GetSourceImg(string filename)
167
168 {
169
170 Image img;
171
172
173
174 img = Bitmap.FromFile(filename);
175
176
177 return img;
178
179 }
180
181
182 #endregion 图片旋转函数