C# 图片处理之:旋转图片任意角度 .
拍摄的数码相片偶尔也有拍歪的时候。没关系,我们还是可以用C#来处理图片。
/// <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;
}
最近论坛里好像有观点认为C#不适合做图片处理。我的观点是:如果不是实时性要求特别高,否则C#可以胜任。
我做了个C#版的个人处理数码相片工具,处理速度令人满意。除了高斯虚化稍慢,别的都很快。
当然前提是要么用BitmapData,要么用GDI+,总之绝对绝对不能用GetPixel/SetPixel。