Here’s a solution that doesn’t change the colorspace of the original image. If you want to normalize the orientation of a grayscale image, you are out of luck with all solutions based on UIGraphicsBeginImageContextWithOptions
because it creates a context in the RGB colorspace. Instead, you have to create a context with the same properties as the original image and draw:
extension UIImage {
static let rotatedOrentations: [UIImage.Orientation] = [.left, .leftMirrored, .right, .rightMirrored]
func normalizedImage() -> UIImage {
if imageOrientation == .up {
return self
}
let image = self.cgImage!
let swapOrientation = UIImage.rotatedOrentations.contains(imageOrientation)
let width = swapOrientation ? image.height : image.width
let height = swapOrientation ? image.width : image.height
let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: image.bitsPerComponent, bytesPerRow: image.bytesPerRow, space: image.colorSpace!, bitmapInfo: image.bitmapInfo.rawValue)!
let flipVertical = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: CGFloat(height));
context.concatenate(flipVertical)
UIGraphicsPushContext(context)
self.draw(at: .zero)
UIGraphicsPopContext()
return UIImage(cgImage: context.makeImage()!)
}
}