How to get a low res image, or Thumbnail from the ALAssetRepresentation in Swift

孤街浪徒 提交于 2019-12-07 05:28:30

问题


I am working with the ALAssetLibrary to get the images from my camera roll for a custom view I am making. Doing so was pretty simple:

library.enumerateGroupsWithTypes(ALAssetsGroupType(ALAssetsGroupSavedPhotos), usingBlock: {
        (group: ALAssetsGroup?, stop: UnsafeMutablePointer<ObjCBool>) in
        if group != nil {
            group!.setAssetsFilter(ALAssetsFilter.allPhotos())
            var indexSet = NSIndexSet(indexesInRange: NSMakeRange(0, group!.numberOfAssets() - 1))
            group!.enumerateAssetsAtIndexes(indexSet, options: nil, usingBlock: {
                (result: ALAsset!, index: Int, stop: UnsafeMutablePointer<ObjCBool>) in
                if (result != nil) {
                    var alAssetRapresentation: ALAssetRepresentation = result.defaultRepresentation()
                    var url = alAssetRapresentation.url()
                    var iRef = alAssetRapresentation.fullResolutionImage().takeUnretainedValue()
                    var image = UIImage(CGImage: iRef)
                }
            })
        }
        }) { (NSError) -> Void in
    }

All this works great in the simulator. However on a device, getting the fullResolutionImage() proves to be way to memory intensive on the device and causes crashes. I figured that makes perfect sense, dozens of high res images all loaded into memory is a terrible idea, so I'd like to scale the quality back and only show the thumbnail of the image. Only issue is that there is no simple way I've found to get a thumbnail from the AlAssetRepresentation.

I am trying to work with the CGImageSourceCreateThumbnailAtIndex to create a thumbnail but have been very confused on how to do this.

Any help is much appreciated!


回答1:


Here's an example (there might be some minor compilation issues, depending what version of Swift you are using):

let src = CGImageSourceCreateWithURL(url, nil)
let scale = UIScreen.mainScreen().scale
let w = // desired display width, multiplied by scale
let d : [NSObject:AnyObject] = [
    kCGImageSourceShouldAllowFloat : true,
    kCGImageSourceCreateThumbnailWithTransform : true,
    kCGImageSourceCreateThumbnailFromImageAlways : true,
    kCGImageSourceThumbnailMaxPixelSize : w
]
let imref = CGImageSourceCreateThumbnailAtIndex(src, 0, d)
let im = UIImage(CGImage: imref, scale: scale, orientation: .Up)!

However, note that you should not be using ALAssetsLibrary any longer. It is deprecated in iOS 9. Switch to Photo Kit, and welcome to the modern world! Now you can call PHImageManager.defaultManager().requestImageForAsset, which allows you to supply a targetSize for the desired image.



来源:https://stackoverflow.com/questions/32190423/how-to-get-a-low-res-image-or-thumbnail-from-the-alassetrepresentation-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!