我试图通过扩展从共享图像创建缩略图,并发现当通过NSItemProvider
提供的URL加载UIImage
,然后通过以下方式创建缩略图:
UIGraphicsImageRenderer(bounds: thumbnailBounds).image { context in
image.draw(in: thumbnailBounds)
}
对于较大的图像,会导致扩展内存溢出(>120mb)。我的解决方案是在从URL直接创建UIImage
之前将图像降采样到适合我的应用程序的像素大小,以便通过共享扩展管理而不会导致内存溢出。
private func resizeForUpload(_ imageURL: URL) -> UIImage? {
let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary
let maxDimensionInPixels: CGFloat = 2000
let downsampleOptions = [kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary
guard let imageSource = CGImageSourceCreateWithURL(imageURL as CFURL, imageSourceOptions), let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else {
return nil
}
return UIImage(cgImage: downsampledImage)
}
这是使用 private func resizeForUpload(_ imageURL: URL) -> UIImage?
的方法。
if itemProvider.hasItemConformingToTypeIdentifier(SystemUTType.image) {
itemProvider.loadItem(forTypeIdentifier: SystemUTType.image, options: nil) { secureCoding, error in
if let url = secureCoding as? URL,
let image = self.resizeForUpload(url) {
completion(image, nil)
} else if let image = secureCoding as? UIImage {
completion(image, nil)
} else if let data = secureCoding as? Data,
let image = UIImage(data: data) {
completion(image, nil)
} else {
completion(nil, error)
}
}