Created
August 17, 2012 17:16
-
-
Save jlyonsmith/3380735 to your computer and use it in GitHub Desktop.
Function to rotate an image using Cairo in C#/Mono.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum ImageRotation | |
{ | |
None, | |
Left, | |
Right, | |
UpsideDown | |
} | |
public class ImageTools | |
{ | |
public static void RotatePng(ParsedPath pngPath, ImageRotation rotation) | |
{ | |
if (rotation == ImageRotation.None) | |
return; | |
using (ImageSurface originalImage = new ImageSurface(pngPath)) | |
{ | |
int w; | |
int h; | |
if (rotation == ImageRotation.Left || rotation == ImageRotation.Right) | |
{ | |
w = originalImage.Height; | |
h = originalImage.Width; | |
} | |
else | |
{ | |
w = originalImage.Width; | |
h = originalImage.Height; | |
} | |
double[] rotationRadians = {0, -Math.PI / 2, Math.PI / 2, Math.PI }; | |
using (ImageSurface rotatedImage = new ImageSurface(Format.Argb32, w, h)) | |
{ | |
using (Cairo.Context g = new Cairo.Context(rotatedImage)) | |
{ | |
g.Translate(rotatedImage.Width / 2.0, rotatedImage.Height / 2.0); | |
g.Rotate(rotationRadians[(int)rotation]); | |
g.Translate(-originalImage.Width / 2.0, -originalImage.Height / 2.0); | |
g.SetSourceSurface(originalImage, 0, 0); | |
g.Paint(); | |
} | |
rotatedImage.WriteToPng(pngPath); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment