Apply orientation to CGContext

643 views Asked by At

I'm scaling down a UIImage using this code:

let image = UIImage(contentsOfFile: imageUrl.path!)!.CGImage

                let width = Float(CGImageGetWidth(image)) / 1.01
                let height = Float(CGImageGetHeight(image)) / 1.01
                let bitsPerComponent = CGImageGetBitsPerComponent(image)
                let bytesPerRow = CGImageGetBytesPerRow(image)
                let colorSpace = CGImageGetColorSpace(image)
                let bitmapInfo = CGImageGetBitmapInfo(image)

                let context = CGBitmapContextCreate(nil, Int(width), Int(height), bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)
                CGContextSetInterpolationQuality(context, kCGInterpolationHigh)

                CGContextDrawImage(context, CGRect(origin: CGPointZero, size: CGSize(width: CGFloat(width), height: CGFloat(height))), image)

                let scaledImage = UIImage(CGImage: CGBitmapContextCreateImage(context))

It's used in a Photo Extension. It works, scales the input image, but does not consider orientation. I keep orientation when editing starts:

func startContentEditingWithInput(contentEditingInput: PHContentEditingInput?, placeholderImage: UIImage) {

        let output = PHContentEditingOutput(contentEditingInput: self.input)
        let url = self.input?.fullSizeImageURL
        if let imageUrl = url {
           imageOrientation = input!.fullSizeImageOrientation
        }

}

The saved output is always landscape.

2

There are 2 answers

0
Maysam On BEST ANSWER

This worked for me:

let scaledImage = UIImage(CGImage: CGBitmapContextCreateImage(context))

                var cimage: CIImage
                cimage = CIImage(image: scaledImage)

                if self.imageOrientation != nil {
                    cimage = cimage.imageByApplyingOrientation(self.imageOrientation!)
                }
                var _context = CIContext(options: nil)

                var cgImage = _context.createCGImage(cimage,
                    fromRect: cimage.extent())

                var resultImage = UIImage(CGImage: cgImage)

Mats' answer does work when I'm saving image.

0
Mats On

The easiest solution is to re-use to image orientation from the UIImage input when creating the UIImage output.

let uiImage = UIImage(contentsOfFile: imageUrl.path!)
let image = uiImage!.CGImage
// ...
let scaledImage = UIImage(CGImage: CGBitmapContextCreateImage(context),
                          scale: uiImage.scale,
                          orientation: uiImage.imageOrientation)