Search code examples
iosuiimageswift4cgimage

Cropping a UIImage makes it rotate 90º anti-clockwise upon saving


I am making an app that has a fullscreen camera with AVFoundation. I was saving the UIImage directly without compressing it. And it gave me the desired output, i.e., it was saving images with the orientation they were taken. But when I tried to crop it to a rect (CGRect), it saved the image like before. Here's what I did:

@objc func saveTapped() {
        myIndicator.isHidden = false
        guard let imageToSave = imageToShow else { return }
        let crop = CGRect(x: 0, y: 0, width: 1440.0, height: 2560.0)
        let croppedCGImage = imageToSave.cgImage?.cropping(to: crop)
        let croppedUIImage = UIImage(cgImage: croppedCGImage!)
        UIImageWriteToSavedPhotosAlbum(croppedUIImage, nil, nil, nil)
        myIndicator.stopAnimating()
    }

I don't know how to save them in my desired orientation. Please help!


Solution

  • Change below line from

    let croppedUIImage = UIImage(cgImage: croppedCGImage)
    

    to

    let croppedUIImage = UIImage(cgImage: croppedCGImage, scale: imageToSave.scale, orientation: imageToSave.imageOrientation)