實現圖片90度整數倍的旋轉
public
static Bitmap KiRotate90(Bitmap img)
{
try
{
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
return img;
}
catch
{
return null;
}
}
//順時針旋轉90度 RotateFlipType.Rotate90FlipNone
//逆時針旋轉90度 RotateFlipType.Rotate270FlipNone
//水平翻轉 RotateFlipType.Rotate180FlipY
//垂直翻轉 RotateFlipType.Rotate180FlipX
{
try
{
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
return img;
}
catch
{
return null;
}
}
//順時針旋轉90度 RotateFlipType.Rotate90FlipNone
//逆時針旋轉90度 RotateFlipType.Rotate270FlipNone
//水平翻轉 RotateFlipType.Rotate180FlipY
//垂直翻轉 RotateFlipType.Rotate180FlipX
/// <summary>
/// 任意角度旋轉
/// </summary>
/// <param name="bmp">原始圖Bitmap</param>
/// <param name="angle">旋轉角度</param>
/// <param name="bkColor">背景色</param>
/// <returns>輸出Bitmap</returns>
public static Bitmap KiRotate(Bitmap bmp, float angle, Color bkColor)
{
int w = bmp.Width + 2;
int h = bmp.Height + 2;
PixelFormat pf;
if (bkColor == Color.Transparent)
{
pf = PixelFormat.Format32bppArgb;
}
else
{
pf = bmp.PixelFormat;
}
Bitmap tmp = new Bitmap(w, h, pf);
Graphics g = Graphics.FromImage(tmp);
g.Clear(bkColor);
g.DrawImageUnscaled(bmp, 1, 1);
g.Dispose();
GraphicsPath path = new GraphicsPath();
path.AddRectangle(new RectangleF(0f, 0f, w, h));
Matrix mtrx = new Matrix();
mtrx.Rotate(angle);
RectangleF rct = path.GetBounds(mtrx);
Bitmap dst = new Bitmap((int)rct.Width, (int)rct.Height, pf);
g = Graphics.FromImage(dst);
g.Clear(bkColor);
g.TranslateTransform(-rct.X, -rct.Y);
g.RotateTransform(angle);
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.DrawImageUnscaled(tmp, 0, 0);
g.Dispose();
tmp.Dispose();
return dst;
}
/// 任意角度旋轉
/// </summary>
/// <param name="bmp">原始圖Bitmap</param>
/// <param name="angle">旋轉角度</param>
/// <param name="bkColor">背景色</param>
/// <returns>輸出Bitmap</returns>
public static Bitmap KiRotate(Bitmap bmp, float angle, Color bkColor)
{
int w = bmp.Width + 2;
int h = bmp.Height + 2;
PixelFormat pf;
if (bkColor == Color.Transparent)
{
pf = PixelFormat.Format32bppArgb;
}
else
{
pf = bmp.PixelFormat;
}
Bitmap tmp = new Bitmap(w, h, pf);
Graphics g = Graphics.FromImage(tmp);
g.Clear(bkColor);
g.DrawImageUnscaled(bmp, 1, 1);
g.Dispose();
GraphicsPath path = new GraphicsPath();
path.AddRectangle(new RectangleF(0f, 0f, w, h));
Matrix mtrx = new Matrix();
mtrx.Rotate(angle);
RectangleF rct = path.GetBounds(mtrx);
Bitmap dst = new Bitmap((int)rct.Width, (int)rct.Height, pf);
g = Graphics.FromImage(dst);
g.Clear(bkColor);
g.TranslateTransform(-rct.X, -rct.Y);
g.RotateTransform(angle);
g.InterpolationMode = InterpolationMode.HighQualityBilinear;
g.DrawImageUnscaled(tmp, 0, 0);
g.Dispose();
tmp.Dispose();
return dst;
}