从症状来看,我假设您正在使用类似的东西来加载您的图像:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
loadImageInMemory(image)
}
picker.dismiss(animated: true, completion: nil)
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
其中loadImageInMemory 是处理图像的函数。
事实证明,如果您使用该方法,存储在 iCloud 上的图像可能会以低于原始质量的质量被检索。验证这种情况的一种方法是更改您的照片设置。在“设置”应用中:
Settings -> Photos -> Download and Keep Originals
这可以解决问题,但当然是不可取的。如果您想继续使用照片,而不是实现自己的 iCloud 解决方案,同时保持Optimize iPhone Storage 设置,您可以使用PhotoKit 检索原始图像。
改用此代码:
import Photos
// ...
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// it will be loaded asynchronously
loadImageFromPicker(info: info)
picker.dismiss(animated: true, completion: nil)
self.presentingViewController?.dismiss(animated: true, completion: nil)
}
private func loadImageFromPicker(info: [UIImagePickerController.InfoKey : Any]) {
var phAsset: PHAsset?
if #available(iOS 11.0, *) {
phAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset
} else {
// Fallback on earlier versions
if let referenceURL = info[UIImagePickerController.InfoKey.referenceURL] as? URL {
let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
phAsset = fetchResult.firstObject
}
}
guard let asset = phAsset else {
return
}
// size doesn't matter, because resizeMode = .none
let size = CGSize(width: 32, height: 32)
let options = PHImageRequestOptions()
options.version = .original
options.deliveryMode = .highQualityFormat
options.resizeMode = .none
options.isNetworkAccessAllowed = true
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: options) { [weak self] (image, info) in
if let s = self, let image = image {
s.loadImageInMemory(image)
}
}
}
此代码适用于本地图像和 iCloud 图像。
这解决了我在处理带有 alpha 的小型 PNG 图像时遇到的类似问题。参考this other post。