UIImageWriteToSavedPhotosAlbum save as PNG with transparency?

前端 未结 5 1828
轻奢々
轻奢々 2020-12-02 14:44

I\'m using UIImageWriteToSavedPhotosAlbum to save a UIImage to the user\'s photo album. The problem is that the image doesn\'t have transparency and is a JPG. I\'ve got the

5条回答
  •  生来不讨喜
    2020-12-02 15:19

    As an alternative to creating a secondary UIImage for UIImageWriteToSavedPhotosAlbum the PNG data can be written directly using the PHPhotoLibrary.

    Here is a UIImage extension named 'saveToPhotos' which does this:

    extension UIImage {
    
        func saveToPhotos(completion: @escaping (_ success:Bool) -> ()) {
    
            if let pngData = self.pngData() {
    
                PHPhotoLibrary.shared().performChanges({ () -> Void in
    
                    let creationRequest = PHAssetCreationRequest.forAsset()
                    let options = PHAssetResourceCreationOptions()
    
                    creationRequest.addResource(with: PHAssetResourceType.photo, data: pngData, options: options)
    
                }, completionHandler: { (success, error) -> Void in
    
                    if success == false {
    
                        if let errorString = error?.localizedDescription  {
                            print("Photo could not be saved: \(errorString))")
                        }
    
                        completion(false)
                    }
                    else {
                        print("Photo saved!")
    
                        completion(true)
                    }
                })
            }
            else {
                completion(false)
            }
    
        }
    }
    

    To use:

        if let image = UIImage(named: "Background.png") {
            image.saveToPhotos { (success) in
                if success {
                    // image saved to photos
                }
                else {
                    // image not saved
                }
            }
        }
    

提交回复
热议问题