Skip to content

Instantly share code, notes, and snippets.

@jlyonsmith
Created August 17, 2012 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlyonsmith/3380735 to your computer and use it in GitHub Desktop.
Save jlyonsmith/3380735 to your computer and use it in GitHub Desktop.
Function to rotate an image using Cairo in C#/Mono.
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