I'm trying to use CGImageSourceCreateThumbnailAtIndex
to efficiently create a resized version of an image. I have some existing code that does this with images from disk, and now I'm trying to use an image that comes from ALAssetsLibrary
.
Here's my code:
ALAsset *asset;
ALAssetRepresentation *representation = [asset defaultRepresentation];
CGImageRef imageRef = [representation fullResolutionImage];
CGDataProviderRef provider = CGImageGetDataProvider(imageRef);
CGImageSourceRef sourceRef = CGImageSourceCreateWithDataProvider(provider, NULL);
NSDictionary *resizeOptions = @{
kCGImageSourceCreateThumbnailWithTransform : @YES,
kCGImageSourceCreateThumbnailFromImageAlways : @YES,
kCGImageSourceThumbnailMaxPixelSize : @(2100)
};
CGImageRef resizedImage = CGImageSourceCreateThumbnailAtIndex(source, 0, resizeOptions);
The problem is that resizedImage
is null, and CGImageSourceGetCount(sourceRef)
returns 0. The data provider does have quite a bit of data in it, though, and the data does appear to be valid image data. The ALAsset
comes from an iPhone 4S camera roll.
What am I missing? Why does CGImageSourceCreateWithDataProvider()
create an image source with 0 images?
CGImageSource is for deserializing serialized images, such as JPEGs, PNGs, and whatnot.
CGImageGetDataProvider
returns (the provider of) the raw pixel data of the image. It does not return serialized bytes in some external format. CGImageSource has no way to know what pixel format (color space, bits-per-component, alpha layout, etc.) any given raw pixel data is in.
You could try getting the URL of the asset rep and giving that to CGImageSourceCreateWithURL
. If that doesn't work (e.g., not a file URL), you'll have to run the image through a CGImageDestination and create a CGImageSource with wherever you put the output.
(The one other thing to try would be to see whether the rep's filename
is actually a full path, the way Cocoa often misuses the term. But you probably shouldn't count on that.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With