Skip to content

Instantly share code, notes, and snippets.

@lvterry
Created March 28, 2016 14:57
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lvterry/f062cf9ae13bca76b0c6 to your computer and use it in GitHub Desktop.
Save lvterry/f062cf9ae13bca76b0c6 to your computer and use it in GitHub Desktop.
Convert PHAsset to UIImage with Swift
// it returns a square thumbnail.
func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
let retinaScale = UIScreen.mainScreen().scale
let retinaSquare = CGSizeMake(size * retinaScale, size * retinaScale)
let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
let square = CGRectMake(0, 0, CGFloat(cropSizeLength), CGFloat(cropSizeLength))
let cropRect = CGRectApplyAffineTransform(square, CGAffineTransformMakeScale(1.0/CGFloat(asset.pixelWidth), 1.0/CGFloat(asset.pixelHeight)))
let manager = PHImageManager.defaultManager()
let options = PHImageRequestOptions()
var thumbnail = UIImage()
options.synchronous = true
options.deliveryMode = .HighQualityFormat
options.resizeMode = .Exact
options.normalizedCropRect = cropRect
manager.requestImageForAsset(asset, targetSize: retinaSquare, contentMode: .AspectFit, options: options, resultHandler: {(result, info)->Void in
thumbnail = result!
})
return thumbnail
}
@nedimf
Copy link

nedimf commented Jun 25, 2020

Swift 5

func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
        let retinaScale = UIScreen.main.scale
        let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)
        let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
        let square = CGRect(x: 0, y: 0, width: CGFloat(cropSizeLength), height: CGFloat(cropSizeLength))
        let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))
        
        let manager = PHImageManager.default()
        let options = PHImageRequestOptions()
        var thumbnail = UIImage()
        
        options.isSynchronous = true
        options.deliveryMode = .highQualityFormat
        options.resizeMode = .exact
        
        options.normalizedCropRect = cropRect
        
        manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
            thumbnail = result!
        })
        return thumbnail
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment