Search code examples
videouiimagepickercontrollerthumbnails

UIImagePickerController thumbnail of video which is pick up from library


I am trying to get the thumbnail of the video which is pick up from library using the UIImagePickerController.

Here is my code. I can get the the thumbnail of video if I using the camera to record a video. But I can not get the thumbnail if I pick up a video from the library. Anybody know why?

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        NSURL *mediaUrl = [info objectForKey:UIImagePickerControllerMediaURL];

        MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:mediaUrl];
        moviePlayer.shouldAutoplay = NO;
        UIImage *thumbnail = [[moviePlayer thumbnailImageAtTime:0.0 timeOption:MPMovieTimeOptionNearestKeyFrame] retain];
        [imageView setImage:thumbnail];  //imageView is a UIImageView

        [moviePlayer release];
        [thumbnail release];
        [self dismissModalViewControllerAnimated:YES];
    }
}

Solution

  • I had a semi-related problem, and eventually abandoned using MPMoviePlayer to generate thumbnails. Try using AVAssetImageGenerator instead. Apple discusses using AVAssetImageGenerator to create thumbnails here. Here is my own sample code, which grabs a single thumbnail image. You will need to include the AVFoundation framework.

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:vidPath options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    [gen release];