在 Swift 中从 UIImage 生成缩略图

Dan*_*rca 3 thumbnails uiimage image-resizing swift

我想获取一个 UIImage 并输出它的 100 x 100 版本以用作缩略图。我找到了一些关于如何在 Objective-C 中做到这一点的答案,但不是很快,并且不知道从哪里开始。我还找到了链接(https://nshipster.com/image-resizing/#technique-3-creating-a-thumbnail-with-image-io),这表明它并不像我希望的那么直接。该链接让我希望其中一种方法可能有效,但每个方法都引用了一个 URL 参数,这让我很困惑,因为我从 UIImage 作为输入开始。

在类似的情况下(用户从手机上传图片),我使用下面的代码从资产创建缩略图,当输入是 UIImage 而不是 PHAsset 时,我正在寻求帮助做同样的事情。

func getAssetThumbnail(asset: PHAsset) -> UIImage {
        let manager = PHImageManager.default()
        let option = PHImageRequestOptions()
        var thumbnail = UIImage()
        option.isSynchronous = true

        manager.requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
            thumbnail = result!
        })
        return thumbnail
    }
Run Code Online (Sandbox Code Playgroud)

Kou*_*iga 5

iOS 15 向 UIImage 添加了以下测试版 API。

func prepareThumbnail(of: CGSize, completionHandler: (UIImage?) -> Void)
func preparingThumbnail(of: CGSize) -> UIImage?
Run Code Online (Sandbox Code Playgroud)

https://developer.apple.com/documentation/uikit/uiimage/