iOS UIImagePickerController result image orientation after upload

后端 未结 20 2266
长发绾君心
长发绾君心 2020-11-22 00:44

I am testing my iPhone application on an iOS 3.1.3 iPhone. I am selecting/capturing an image using a UIImagePickerController:

UIImagePickerCont         


        
20条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 01:04

    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()!)
        }
    }
    

提交回复
热议问题