Losing image orientation while converting an image to CGImage

后端 未结 7 2108
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-31 04:30

I\'m facing an image orientation issue when cropping a square portion of an image out of a rectangular original image. When image is in landscape, it\'s fine. But when it is

7条回答
  •  旧时难觅i
    2020-12-31 05:18

    Here's a UIImage extension I wrote after looking after looking at several older pieces of code written by others. It's written in Swift 3 and uses the iOS orientation property plus CGAffineTransform to re-draw the image in proper orientation.

    SWIFT 3:

    public extension UIImage {
    
        /// Extension to fix orientation of an UIImage without EXIF
        func fixOrientation() -> UIImage {
    
            guard let cgImage = cgImage else { return self }
    
            if imageOrientation == .up { return self }
    
            var transform = CGAffineTransform.identity
    
            switch imageOrientation {
    
            case .down, .downMirrored:
                transform = transform.translatedBy(x: size.width, y: size.height)
                transform = transform.rotated(by: CGFloat(M_PI))
    
            case .left, .leftMirrored:
                transform = transform.translatedBy(x: size.width, y: 0)
                transform = transform.rotated(by: CGFloat(M_PI_2))
    
            case .right, .rightMirrored:
                transform = transform.translatedBy(x: 0, y: size.height)
                transform = transform.rotated(by: CGFloat(-M_PI_2))
    
            case .up, .upMirrored:
                break
            }
    
            switch imageOrientation {
    
            case .upMirrored, .downMirrored:
                transform.translatedBy(x: size.width, y: 0)
                transform.scaledBy(x: -1, y: 1)
    
            case .leftMirrored, .rightMirrored:
                transform.translatedBy(x: size.height, y: 0)
                transform.scaledBy(x: -1, y: 1)
    
            case .up, .down, .left, .right:
                break
            }
    
            if let ctx = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0, space: cgImage.colorSpace!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) {
    
                ctx.concatenate(transform)
    
                switch imageOrientation {
    
                case .left, .leftMirrored, .right, .rightMirrored:
                    ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
    
                default:
                    ctx.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
                }
    
                if let finalImage = ctx.makeImage() {
                    return (UIImage(cgImage: finalImage))
                }
            }
    
            // something failed -- return original
            return self
        }
    }
    

提交回复
热议问题