C#快速无损失图像旋转

本文关键字:图像 旋转 损失 | 更新日期: 2023-09-27 18:21:16

我需要将图像旋转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));
}

C#快速无损失图像旋转

使用图形gfx旋转。如果你使用RotateFlip,你会付出很多额外的努力。对于图像转换,使用图形而不是图像。它更快更有效。图形非常强大,可以让你非常容易地进行图像处理。

gfx.RotateTransform(rotationAngle);