iosswiftuiimageavfoundationuiimageorientation

Saving a photo issue with .leftMirrored orientation


So I am saving two photos using this function

let leftMirroredImage = UIImage(cgImage: myImage.cgImage!, scale: myImage.scale, orientation: UIImageOrientation.leftMirrored)

UIImageWriteToSavedPhotosAlbum(myImage, nil, nil, nil)
UIImageWriteToSavedPhotosAlbum(leftMirroredImage, nil, nil, nil) . 

but for some reason, the leftMirroredImage is getting cut off when I view it in the Photos app. like so enter image description here .

here is the normal image that was saved enter image description here

I also noticed that the photo will get cut off like that with .upMirrored , .downMirrored, and .rightMirrored. Any idea why this is happening?


Solution

  • You can use CIFilter "CIAffineTransform" and multiply your image x scale by -1 to flip your image horizontally:

    let image = UIImage(data: try! Data(contentsOf: URL(string:"https://i.sstatic.net/Xs4RX.jpg")!))!
    let transform = CGAffineTransform(scaleX: -1, y: 1)
    if let ciimage = CIImage(image: image),
        let flipped = CIFilter(name: "CIAffineTransform", withInputParameters: [kCIInputImageKey: ciimage, kCIInputTransformKey: NSValue(cgAffineTransform: transform)])?.outputImage {
        let image = UIImage(ciImage: flipped)
        UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
        image.draw(in: CGRect(origin: .zero, size: image.size))
        let flippedUIImage =  UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }