Preserve your images' transparency when saving and sharing them, in Swift

Loosing your rounded corners or transparent background when saving an image to the user's photo library or sharing it with UIActivityViewController? It's because it's be turned into a JPEG. Here's how to solve that.

Preserve your images' transparency when saving and sharing them, in Swift
Photo by Bud Helisson / Unsplash

Let's say we are making an app. A chat app, a social media where the main medium are pictures, an image generation app using the latest GAN models machine learning has to offer, whatever. It's an iOS app, written in Swift, it shows images, and users can save those locally and re-share them through other apps, without losing the alpha (the transparency).

How do we preserve said alpha? We save those images as PNG images instead of JPEG.

How do we save an UIImage as a PNG image in Swift? Easy:

func pngImage(image: UIImage) -> UIImage? {
        guard let data = image.pngData(),
              let pngImage = UIImage(data: data) else {
            return nil
        }
        return pngImage
    }
    
func savePngImage(image: UIImage) {
	guard let pngImage = pngImage(image) else {
    	return
    }
    UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil)
}

Now, how do we share a PNG image in Swift? Even easier:

func sharePngImage(image: UIImage) {
    let activityItems = [image.pngData()]
    let activityVC = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
    UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
}

Yes, that's it. No long story, no contrived explanations. Just what you (and future me) need! I hope it helped, and wish you all a great day!

Two pina coladas, a pineapple and some pieces of cococunut on a table on a beach. In the background, a sandy beach and the sun setting over the ocean.
A pina colada by the beach, as imagined by a drunken AI. In jpg, because eating up 2MB of bandwidth for that would be plain rude.