UIImageView not showing transparency of PNG Images from UIImagePickerController

后端 未结 3 871
忘掉有多难
忘掉有多难 2020-12-07 02:21

I surely hope I am missing something because I do not understand why this is working the way it does. I have a PNG Image, which has a fully transparent background because I

3条回答
  •  孤街浪徒
    2020-12-07 02:31

    Yes, the call to UIImageJPEGRepresentation will convert the resulting image into a JPEG, which doesn't support transparency.

    BTW, if your intent is to get the NSData for the image for other reasons (e.g. uploading to server, emailing, etc.), I would recommend against both UIImageJPEGRepresentation and UIImagePNGRepresentation. They lose meta data, can make the asset larger, if suffer some image degradation if you use quality factor of less than 1, etc.

    Instead, I'd recommend going back and get the original asset from the Photos framework. Thus, in Swift 3:

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let url = info[UIImagePickerControllerReferenceURL] as? URL {
            let result = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
            if let asset = result.firstObject {
                let manager = PHImageManager.default()
                manager.requestImageData(for: asset, options: nil) { imageData, dataUTI, orientation, info in
                    if let fileURL = info!["PHImageFileURLKey"] as? URL {
                        let filename = fileURL.lastPathComponent
                        // use filename here
                    }
    
                    // use imageData here
                }
            }
        }
    
        picker.dismiss(animated: true)
    }
    

    If you have to support iOS 7, too, you'd use the equivalent ALAssetsLibrary API, but the idea is the same: Get the original asset rather than round-tripping it through a UIImage.

    (For Swift 2 rendition, see previous revision of this answer.)

提交回复
热议问题