C# 任意角度旋轉 Bitmap 範例
C# 任意角度旋轉 Bitmap 範例
資料來源: chatgpt
code
public static Bitmap RotateImage(Bitmap bmp, float angle)
{
// 建立一個新的空白 Bitmap,足以容納旋轉後的圖
int w = bmp.Width;
int h = bmp.Height;
double rad = angle * Math.PI / 180;
double cos = Math.Abs(Math.Cos(rad));
double sin = Math.Abs(Math.Sin(rad));
int newW = (int)(w * cos + h * sin);
int newH = (int)(w * sin + h * cos);
Bitmap rotatedBmp = new Bitmap(newW, newH);
rotatedBmp.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);
using (Graphics g = Graphics.FromImage(rotatedBmp))
{
g.TranslateTransform(newW / 2f, newH / 2f); // 移動到中心
g.RotateTransform(angle); // 旋轉
g.TranslateTransform(-w / 2f, -h / 2f); // 移回圖片原點
g.DrawImage(bmp, new Point(0, 0));
}
return rotatedBmp;
}