Preserve your images' transparency when saving and sharing them, in Swift
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!