Created
January 5, 2017 13:07
-
-
Save JigarM/c481a4c21fc3a11cd212c7d427cb9de7 to your computer and use it in GitHub Desktop.
Scale and Rotate an image in iOS / MonoTouch, using the EXIF data.
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
//MIT license | |
//https://gist.github.com/nicwise/890460 | |
public static UIImage ScaleImage(UIImage image, int maxSize) | |
{ | |
UIImage res; | |
using (CGImage imageRef = image.CGImage) | |
{ | |
CGImageAlphaInfo alphaInfo = imageRef.AlphaInfo; | |
CGColorSpace colorSpaceInfo = CGColorSpace.CreateDeviceRGB(); | |
if (alphaInfo == CGImageAlphaInfo.None) | |
{ | |
alphaInfo = CGImageAlphaInfo.NoneSkipLast; | |
} | |
int width, height; | |
width = imageRef.Width; | |
height = imageRef.Height; | |
if (height >= width) | |
{ | |
width = (int)Math.Floor((double)width * ((double)maxSize / (double)height)); | |
height = maxSize; | |
} | |
else | |
{ | |
height = (int)Math.Floor((double)height * ((double)maxSize / (double)width)); | |
width = maxSize; | |
} | |
CGBitmapContext bitmap; | |
if (image.Orientation == UIImageOrientation.Up || image.Orientation == UIImageOrientation.Down) | |
{ | |
bitmap = new CGBitmapContext(IntPtr.Zero, width, height, imageRef.BitsPerComponent, imageRef.BytesPerRow, colorSpaceInfo, alphaInfo); | |
} | |
else | |
{ | |
bitmap = new CGBitmapContext(IntPtr.Zero, height, width, imageRef.BitsPerComponent, imageRef.BytesPerRow, colorSpaceInfo, alphaInfo); | |
} | |
switch (image.Orientation) | |
{ | |
case UIImageOrientation.Left: | |
bitmap.RotateCTM((float)Math.PI / 2); | |
bitmap.TranslateCTM(0, -height); | |
break; | |
case UIImageOrientation.Right: | |
bitmap.RotateCTM(-((float)Math.PI / 2)); | |
bitmap.TranslateCTM(-width, 0); | |
break; | |
case UIImageOrientation.Up: | |
break; | |
case UIImageOrientation.Down: | |
bitmap.TranslateCTM(width, height); | |
bitmap.RotateCTM(-(float)Math.PI); | |
break; | |
} | |
bitmap.DrawImage(new Rectangle(0, 0, width, height), imageRef); | |
res = UIImage.FromImage(bitmap.ToImage()); | |
bitmap = null; | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment