Rotate photo with SkiaSharp

Viewed 6824

I'm trying to rotate photo with SkiaSharp to 90 degrees with following code:

    public SKBitmap Rotate()
    {
        var bitmap = SKBitmap.Decode("test.jpg");
        using (var surface = new SKCanvas(bitmap))
        {
            surface.RotateDegrees(90, bitmap.Width / 2, bitmap.Height / 2);
            surface.DrawBitmap(bitmap.Copy(), 0, 0);
        }

        return bitmap;
     }

But when I save bitmap to JPEG file, it has margins both on top and bottom of image.

Original image: http://imgur.com/pGAuko8. Rotated image: http://imgur.com/bYxpmI7.

What am I doing wrong?

2 Answers

Matthew's solution works for me too, but i had an issue when i tried to rotate bitmaps more than 90° or -90° (bitmap was drawed "out of display"). I highly recommend using this solution. Slightly modified result:

public static SKBitmap Rotate(SKBitmap bitmap, double angle)
    {
        double radians = Math.PI * angle / 180;
        float sine = (float)Math.Abs(Math.Sin(radians));
        float cosine = (float)Math.Abs(Math.Cos(radians));
        int originalWidth = bitmap.Width;
        int originalHeight = bitmap.Height;
        int rotatedWidth = (int)(cosine * originalWidth + sine * originalHeight);
        int rotatedHeight = (int)(cosine * originalHeight + sine * originalWidth);

        var rotatedBitmap = new SKBitmap(rotatedWidth, rotatedHeight);

        using (var surface = new SKCanvas(rotatedBitmap))
        {
            surface.Translate(rotatedWidth / 2, rotatedHeight / 2);
            surface.RotateDegrees((float)angle);
            surface.Translate(-originalWidth / 2, -originalHeight / 2);
            surface.DrawBitmap(bitmap, new SKPoint());
        }
        return rotatedBitmap;
    }

In my case I used this when I needed rotate picture on the Xamarin.iOS platform (who ever tried this, knows), works like a charm.

Related