How can I save a PHLivePhoto to photo library?

613 Views Asked by At

I am new in Swift and I am developing an app that picks a live photo from the library and displays it on an imageview, until that part it works, but the imageview is on top of another imageview that has a custom image(like a background image). By the moment when I hit the save button it only stores the image view with the custom background. I am using the following code to store it on the library:

let imageData = UIImagePNGRepresentation(myView.image!)
let compressedImage = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compressedImage!, nil, nil, nil)

This code is of course on the save button.

what I want to do is to give the user that ability to store both things at the same time, like for example:

I have an imageview with an image of a galaxy as background and on top of it I have an imageview displaying a live photo, so I want to store both things to the library and when I check it on the library I will have a new live photo with a background of a galaxy.

I don't know if somebody will understand the example, but is I think it is the best I can do to describe the problem.

** this is the example

enter image description here

1

There are 1 best solutions below

8
On

You need to draw the selectedImage on top of the backgroundImage, and save the result.

Add this extension of UIImage

extension UIImage {
    func saveImage(withImage image: UIImage) -> UIImage? {
        // create image
        UIGraphicsBeginImageContext(size)
        draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let centeredFrame = CGRect(x: (size.width - image.size.width)/2, y: (size.height - image.size.height)/2, width: image.size.width, height: image.size.height)
        image.draw(in: centeredFrame)
        let result = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return result
    }
}

And use it

if let newImage = backgroundImage.saveImage(withImage: userImage), let imageData = UIImagePNGRepresentation(newImage), let compressedImage = UIImage(data: imageData) {
    UIImageWriteToSavedPhotosAlbum(compressedImage, nil, nil, nil)
}

Where backgroundImage is custom background and userImage is live photo selected from user library.