Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save haikieu/99407784770c1a3eb8b24dcade72970f to your computer and use it in GitHub Desktop.
Save haikieu/99407784770c1a3eb8b24dcade72970f to your computer and use it in GitHub Desktop.
Extension to fix orientation of an UIImage (Sets orientation to portrait)
extension UIImage {
///UIImage instance somtimes can be at any various orientation, so this method basically converts it back to default orientation.
///This is picked from the original source -> https://gist.github.com/schickling/b5d86cb070130f80bb40
func fixedOrientation() -> UIImage? {
guard imageOrientation != UIImageOrientation.up else {
//This is correct orientation, don't need to do anything
return self.copy() as? UIImage
}
guard let cgImage = self.cgImage else {
//CGImage is not available
return nil
}
guard let colorSpace = cgImage.colorSpace, let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
return nil //Not able to create CGContext
}
var transform: CGAffineTransform = CGAffineTransform.identity
switch imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: CGFloat.pi)
break
case .left, .leftMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: CGFloat.pi / 2.0)
break
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: CGFloat.pi / -2.0)
break
case .up, .upMirrored:
break
}
//Flip image one more time to if needed to prevent flipped image
switch imageOrientation {
case .upMirrored, .downMirrored:
transform.translatedBy(x: size.width, y: 0)
transform.scaledBy(x: -1, y: 1)
break
case .leftMirrored, .rightMirrored:
transform.translatedBy(x: size.height, y: 0)
transform.scaledBy(x: -1, y: 1)
case .up, .down, .left, .right:
break
}
ctx.concatenate(transform)
switch imageOrientation {
case .left, .leftMirrored, .right, .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
}
guard let newCGImage = ctx.makeImage() else { return nil }
return UIImage.init(cgImage: newCGImage, scale: 1, orientation: .up)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment