My main problem is i need to obtain a thumbnail for an ALAsset object.
I tried a lot of solutions and searched stack overflow for days, all the solutions i found are not working for me due to these constraint:
- I can’t use the default thumbnail because it’s too little;
- I can’t use the fullScreen or fullResolution image because i have a lot of images on screen;
- I can’t use UIImage or UIImageView for resizing because those loads
the fullResolution image - I can’t load the image in memory, i’m working with 20Mpx images;
- I need to create a 200×200 px version of the original asset to load on screen;
this is the last iteration of the code i came with:
#import <AssetsLibrary/ALAsset.h>
#import <ImageIO/ImageIO.h>
// ...
ALAsset *asset;
// ...
ALAssetRepresentation *assetRepresentation = [asset defaultRepresentation];
NSDictionary *thumbnailOptions = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kCFBooleanTrue, kCGImageSourceCreateThumbnailWithTransform,
(id)kCFBooleanTrue, kCGImageSourceCreateThumbnailFromImageAlways,
(id)[NSNumber numberWithFloat:200], kCGImageSourceThumbnailMaxPixelSize,
nil];
CGImageRef generatedThumbnail = [assetRepresentation CGImageWithOptions:thumbnailOptions];
UIImage *thumbnailImage = [UIImage imageWithCGImage:generatedThumbnail];
problem is, the resulting CGImageRef is neither transformed by orientation, nor of the specified max pixel size;
I also tried to find a way of resizing using CGImageSource, but:
- the asset url can’t be used in the
CGImageSourceCreateWithURL:; - i can’t extract from
ALAssetorALAssetRepresentationaCGDataProviderRefto use withCGImageSourceCreateWithDataProvider:; CGImageSourceCreateWithData:requires me to store the fullResolution or fullscreen asset in memory in order to work.
Am i missing something?
Is there another way of obtaining a custom thumbnail from ALAsset or ALAssetRepresentation that i’m missing?
Thanks in advance.
You can use
CGImageSourceCreateThumbnailAtIndexto create a small image from a potentially-large image source. You can load your image from disk using theALAssetRepresentation‘sgetBytes:fromOffset:length:error:method, and use that to create a CGImageSourceRef.Then you just need to pass the
kCGImageSourceThumbnailMaxPixelSizeandkCGImageSourceCreateThumbnailFromImageAlwaysoptions toCGImageSourceCreateThumbnailAtIndexwith the image source you’ve created, and it will create a smaller version for you without loading the huge version into memory.I’ve written a blog post and gist with this technique fleshed out in full.