问题
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