简体   繁体   中英

C# fast loseless image rotation

I need to rotate an image by 90, 180 and 270 degrees. For 180 degree rotation can be used simple RotateFlip(RotateFlipType.Rotate180FlipNone) , but for 90 and 270 i can't find a suitable algorithm.

Various algorithms like

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;
}

seems to be lowering the image quality during resize.

I tried to make it head-on like

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));

but it takes about 20 seconds to rotate an 3600x2400 image.

How can I rotate an image without lowering its quality and fast at the same time?

Why do my algorithm is so inefficient?

UPD:

Trying to make this code work:

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));
}

Rotate with Graphics gfx. If you use RotateFlip you have a lot of extra effort. For image transformations use graphics not image. Its faster and more effective. Graphics are very powerful and allow you to do image manipulation really easily.

gfx.RotateTransform(rotationAngle);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM