Skip to content

Instantly share code, notes, and snippets.

@clooth
Created September 11, 2013 13:47
Show Gist options
  • Select an option

  • Save clooth/6523856 to your computer and use it in GitHub Desktop.

Select an option

Save clooth/6523856 to your computer and use it in GitHub Desktop.
Thumbnail generator from assets
- (CGImageRef)thumbnailImageForAsset:(ALAsset *)asset
maxPixelSize:(NSUInteger)size
{
NSParameterAssert(asset != nil);
NSParameterAssert(size > 0);
ALAssetRepresentation *assetRepresentation = [asset defaultRepresentation];
CGDataProviderDirectCallbacks callbacks = {
.version = 0,
.getBytePointer = NULL,
.releaseBytePointer = NULL,
.getBytesAtPosition = getAssetBytesCallback,
.releaseInfo = releaseAssetCallback,
};
CGDataProviderRef dataProvider = CGDataProviderCreateDirect((void *)CFBridgingRetain(assetRepresentation), [assetRepresentation size], &callbacks);
CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider(dataProvider, NULL);
NSDictionary *thumbnailOptions = @{
(NSString *)kCGImageSourceCreateThumbnailFromImageAlways:
@YES,
(NSString *)kCGImageSourceThumbnailMaxPixelSize:
[NSNumber numberWithInt:size],
(NSString *)kCGImageSourceCreateThumbnailWithTransform:
@YES
};
CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, (__bridge CFDictionaryRef)(thumbnailOptions));
CFRelease(imageSource);
CFRelease(dataProvider);
if (!imageRef) {
return nil;
}
return imageRef;
}
// Helper methods for thumbnailForAsset:maxPixelSize:
static size_t getAssetBytesCallback(void *info, void *buffer, off_t position, size_t count) {
ALAssetRepresentation *rep = (__bridge id)info;
NSError *error = nil;
size_t countRead = [rep getBytes:(uint8_t *)buffer fromOffset:position length:count error:&error];
if (countRead == 0 && error) {
NSLog(@"thumbnailForAsset:maxPixelSize: got an error reading an asset: %@", error);
}
return countRead;
}
static void releaseAssetCallback(void *info) {
CFRelease(info);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment