Forked from schickling/UIImageFixedOrientationExtension.swift
Created
January 19, 2017 09:36
-
-
Save matthiasnagel/fe7ed96dc66310c67b45fb759cf6de8c to your computer and use it in GitHub Desktop.
Extension to fix orientation of an UIImage (Sets orientation to portrait)
This file contains hidden or 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
import UIKit | |
extension UIImage { | |
public func fixedOrientation() -> UIImage { | |
if imageOrientation == UIImageOrientation.up { | |
return self | |
} | |
var transform: CGAffineTransform = CGAffineTransform.identity | |
switch imageOrientation { | |
case UIImageOrientation.down, UIImageOrientation.downMirrored: | |
transform = transform.translatedBy(x: size.width, y: size.height) | |
transform = transform.rotated(by: CGFloat(M_PI)) | |
break | |
case UIImageOrientation.left, UIImageOrientation.leftMirrored: | |
transform = transform.translatedBy(x: size.width, y: 0) | |
transform = transform.rotated(by: CGFloat(M_PI_2)) | |
break | |
case UIImageOrientation.right, UIImageOrientation.rightMirrored: | |
transform = transform.translatedBy(x: 0, y: size.height) | |
transform = transform.rotated(by: CGFloat(-M_PI_2)) | |
break | |
case UIImageOrientation.up, UIImageOrientation.upMirrored: | |
break | |
} | |
switch imageOrientation { | |
case UIImageOrientation.upMirrored, UIImageOrientation.downMirrored: | |
transform.translatedBy(x: size.width, y: 0) | |
transform.scaledBy(x: -1, y: 1) | |
break | |
case UIImageOrientation.leftMirrored, UIImageOrientation.rightMirrored: | |
transform.translatedBy(x: size.height, y: 0) | |
transform.scaledBy(x: -1, y: 1) | |
case UIImageOrientation.up, UIImageOrientation.down, UIImageOrientation.left, UIImageOrientation.right: | |
break | |
} | |
let ctx: CGContext = CGContext(data: nil, | |
width: Int(size.width), | |
height: Int(size.height), | |
bitsPerComponent: self.cgImage!.bitsPerComponent, | |
bytesPerRow: 0, | |
space: self.cgImage!.colorSpace!, | |
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! | |
ctx.concatenate(transform) | |
switch imageOrientation { | |
case UIImageOrientation.left, UIImageOrientation.leftMirrored, UIImageOrientation.right, UIImageOrientation.rightMirrored: | |
ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width)) | |
default: | |
ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) | |
break | |
} | |
let cgImage: CGImage = ctx.makeImage()! | |
return UIImage(cgImage: cgImage) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//Thanks It is great, I have just rewrote it in C#:
UIImage CorrectOrintation(UIImage img)
{
if ((img.Orientation == UIImageOrientation.Up))
{
return img;
}