简体   繁体   中英

How to save an image with transparent background to photo library, Swift?

I'm trying to save some transparent images to photo library but they all saved with white background. All images are png file in my assets folder.

func saveWp() {

    for number in count{
        let wp = UIImage(named: "neon\(number)")!
        let imageSaver = ImageSaver()
        imageSaver.writeToPhotoAlbum(image: wp)
    }
}

class ImageSaver: NSObject {
func writeToPhotoAlbum(image: UIImage) {
    UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveError), nil)
}

@objc func saveError(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
    print("Save finished!")
}

}

In order to preserve the transparent parts of your image you need to include the alpha channel.

Only some file formats allow you to include an alpha channel. JPEG does not. It looks like HEIC format does support alpha, but I couldn't find a way to save HEIC files with alpha after a few minutes of googling.

The PNG file format does support alpha channels. You should be able to save your image to the camera roll as a PNG with alpha. Check out the UIImage function pngData() .

If you use your source image to create a PNG version using pngData() , you should be able to save it to the camera roll and preserve the alpha channel. (Disclaimer: I found the code below in another SO post , and haven't tested it. I changed it to use pngData() instead of UIImagePNGRepresentation()

let imData = image.pngData()
let image2 = UIImage(data: imData)
UIImageWriteToSavedPhotosAlbum(image2, nil, nil, nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM