C#快速失去图像旋转

时间:2015-11-10 09:27:08

标签: c# image rotation

我需要将图像旋转90度,180度和270度。对于180度旋转,可以使用简单RotateFlip(RotateFlipType.Rotate180FlipNone),但对于90和270,我找不到合适的算法。

各种算法,如

public Image RotateImage(Image img)
{
    var bmp = new Bitmap(img);

    using (Graphics gfx = Graphics.FromImage(bmp))
    {
        gfx.Clear(Color.White);
        gfx.DrawImage(img, 0, 0, img.Width, img.Height);
    }

    bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
    return bmp;
}

似乎在调整大小期间降低了图像质量。

我试着像

一样正面对待
result = new Bitmap(source, new Size(source.Height, source.Width));
for (int i = 0; i < source.Height; i++)
    for (int j = 0; j < source.Width; j++)
        result.SetPixel(i, j, source.GetPixel(j, source.Height - i - 1));

但旋转3600x2400图像大约需要20秒。

如何在不降低图像质量的同时快速旋转图像?

为什么我的算法效率低下?

UPD:

尝试使此代码有效:

result = new Bitmap(source.Height, source.Width, source.PixelFormat);
using (Graphics g = Graphics.FromImage(result))
{
    g.TranslateTransform((float)source.Width / 2, (float)source.Height / 2);
    g.RotateTransform(90);
    g.TranslateTransform(-(float)source.Width / 2, -(float)source.Height / 2);
    g.DrawImage(source, new Point(0, 0));
}

1 个答案:

答案 0 :(得分:2)

使用Graphics gfx旋转。如果您使用RotateFlip,则需要付出额外的努力。 对于图像变换,使用图形而不是图像。它更快,更有效。 图形非常强大,可以让您轻松地进行图像处理。

gfx.RotateTransform(rotationAngle);
相关问题