13

我正在尝试从 a 中选择的视频中获取第一帧UIImagePickerController以显示在 a 中UIImageView,但我不知道这是否可能。如果是,我会怎么做?

4

1 回答 1

28

您可以通过以下两种方式之一执行此操作。第一种方法是使用MPMoviePlayerController来抓取缩略图:

MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc]
                                       initWithContentURL:videoURL];
moviePlayer.shouldAutoplay = NO;
UIImage *thumbnail = [moviePlayer thumbnailImageAtTime:time
                     timeOption:MPMovieTimeOptionNearestKeyFrame];

这可行,但MPMoviePlayerController不是一个特别轻量级的对象,也不是特别快速抓取缩略图。

首选方法是使用AVAssetImageGeneratorAVFoundation 中的 new。这比旧方式快速、轻量且更灵活。这是一个帮助方法,它将从视频中返回一个自动发布的图像。


+ (UIImage *)thumbnailImageForVideo:(NSURL *)videoURL 
                             atTime:(NSTimeInterval)time 
{

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetIG = 
                [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetIG.appliesPreferredTrackTransform = YES;
    assetIG.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;

    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *igError = nil;
    thumbnailImageRef = 
             [assetIG copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)
                             actualTime:NULL
                                  error:&igError];

    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", igError );

    UIImage *thumbnailImage = thumbnailImageRef 
                          ? [[UIImage alloc] initWithCGImage:thumbnailImageRef]
                          : nil;

    return thumbnailImage;
}

异步使用


- (void)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time completion:(void (^)(UIImage *)) completion
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
        NSParameterAssert(asset);
        AVAssetImageGenerator *assetIG =
        [[AVAssetImageGenerator alloc] initWithAsset:asset];
        assetIG.appliesPreferredTrackTransform = YES;
        assetIG.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;

        CGImageRef thumbnailImageRef = NULL;
        CFTimeInterval thumbnailImageTime = time;
        NSError *igError = nil;
        thumbnailImageRef =
        [assetIG copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)
                        actualTime:NULL
                             error:&igError];

        if (!thumbnailImageRef)
            NSLog(@"thumbnailImageGenerationError %@", igError );

        UIImage *thumbnailImage = thumbnailImageRef
        ? [[UIImage alloc] initWithCGImage:thumbnailImageRef]
        : nil;

        dispatch_async(dispatch_get_main_queue(), ^{
            completion(thumbnailImage);
        });
    });
}
于 2011-05-12T21:48:09.917 回答