Thursday 12 July 2012

How do I get a thumbnail from UIImagePickerController

The code below will function to take an asset-library URL and then make a UIImage out of the thumbnail representation. Though I use the asset-library url directly there is no reason that this same code couldn't begin by transforming a string representation into a NSURL in order to satisfy the imageURL assignment. Disclaimer: this code probably leaks or something worse, but it answers the original poster's question and is hopefully of value.
The code below is borrowing heavily on this Stack Overflow question that covers basically this same topic. In addition to the code here, I have included AssetsLibrary.framework and the ALAssetsLibrary typedefs referenced in the other question.
The whole trick is that you cannot reference the NSURL from an asset-library directly. I think (though I don't know) that it is somehow referencing a data store instead of a file so the data returned from the URL isn't straight NSData so you cannot use it the old way.
There is a UIImageView in the code that is called photo. Hopefully everything else is easy to figure out.


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    NSLog(@"%@",imageURL);
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        CGImageRef iref = [myasset thumbnail];
        if (iref) {
            UIImage *theThumbnail = [UIImage imageWithCGImage:iref];
            [[self photo] setImage:theThumbnail];

        }
    };


    ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
    {
        NSLog(@"booya, cant get image - %@",[myerror localizedDescription]);
    };

    if(imageURL)
    {
        ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
        [assetslibrary assetForURL:imageURL 
                       resultBlock:resultblock
                      failureBlock:failureblock];
    }

    [self dismissModalViewControllerAnimated:YES];
}

No comments:

Post a Comment