ocean hancock
ocean hancock

Reputation: 137

How to flip image horizontally to save flipped in photo album?

I have been trying to flip an UIImage image horizontally so that i can save it in my photo album, everything is working fine and I am able to save the image to photo album but the image although appears flipped in my app is not saved as flipped in the photo album. I am using following code to flip the image:

myImage?.withHorizontallyFlippedOrientation()

Note: I am not trying to flip the UIImageView, I am trying to flip the image and save it to a new image variable and assigning the image from that image variable to UIImageView.

Complete IBAction Code:

@IBAction func horizontalFlipBtnPressed(_ sender: Any) {
    if myImageView.image != nil{
    let image = myImageView.image
    tempImage.append((image?.withHorizontallyFlippedOrientation())!)

    myImageView.image = tempImage.last



    }
    else{
        print ("there is no image selected")
    }
}

Code for saving in Photos Album:

if myImageView.image != nil{
        var image = myImageView.image
        let imageData = image!.pngData()
        let compressedImage = UIImage(data: imageData!)
        UIImageWriteToSavedPhotosAlbum(compressedImage!, nil, nil, nil)
        let alert = UIAlertController(title: "Saved", message: "Your image has been saved!", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alert.addAction(okAction)
        self.present(alert, animated: true,completion: nil)

    }

Upvotes: 1

Views: 1764

Answers (1)

DonMag
DonMag

Reputation: 77433

From Apple's docs :

Image orientation affects the way the image data is displayed when drawn.

So that doesn't actually affect the image data.

If you just want to "flip the orientation" in the image's metadata, you can use .withHorizontallyFlippedOrientation() and then just save the image (instead of translating it to png data and back).

If you really want the image data (the pixels) flipped, you need to draw it flipped and then save that image. One way to do it:

func flipImageLeftRight(_ image: UIImage) -> UIImage? {

    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
    let context = UIGraphicsGetCurrentContext()!
    context.translateBy(x: image.size.width, y: image.size.height)
    context.scaleBy(x: -image.scale, y: -image.scale)

    context.draw(image.cgImage!, in: CGRect(origin:CGPoint.zero, size: image.size))

    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return newImage
}

Upvotes: 4

Related Questions