Why does PHImageManager() change the image extension and degrade the image quality when I retrieve images from the photo library?

Viewed 30

When I use PHImageManager() to retrieve an image from the photo library, the image is converted from a jpeg image to a png image, and the image is degraded. How can I retrieve the image without image degradation? Is it a standard specification that the extension is changed from jpeg to png? If anyone knows, please respond.

Here is a sample code I made. img is returned as png.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let assets: PHFetchResult = PHAsset.fetchAssets(with: .image, options: nil)
        let mg: PHImageManager = PHImageManager()
        
        guard let asset = assets.lastObject else {
            return
        }
        
        let options = PHImageRequestOptions()
        options.isNetworkAccessAllowed = true
        options.deliveryMode = .highQualityFormat
        
        mg.requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: options, resultHandler: { image, info in
            let img = image
        })
    }
}
1 Answers

When requesting a high quality image, the result handler of requestImage may be called initially with a low quality version of the image, then later called again with the high quality version.

You can check this by inspecting the PHImageResultIsDegradedKey of the info dictionary parameter of the result handler, for example:

mg.requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: options, resultHandler: { image, info in
    if info?[PHImageResultIsDegradedKey] as? Bool == true {
        print("Degraded image returned, will wait for high quality image")
        return
    }
    let img = image
})

From the documentation for PHImageManager.requestImage:

[...] Photos may call your result handler block more than once. Photos first calls the block to provide a low-quality image suitable for displaying temporarily while it prepares a high-quality image. (If low-quality image data is immediately available, the first call may occur before the method returns.) When the high-quality image is ready, Photos calls your result handler again to provide it. If the image manager has already cached the requested image at full quality, Photos calls your result handler only once. The PHImageResultIsDegradedKey key in the result handler’s info parameter indicates when Photos is providing a temporary low-quality image.

Related