从 iOS 中的视频 url 或数据获取缩略图

问题描述:

我试图从 iphone 3GS 相机拍摄的视频中获取缩略图(第一帧的),以便我可以显示它.如何做到这一点?

I am trying to acquire a thumbnail (of the first frame) from a video taken from iphone 3GS camera so I can display it. How to do this?

这个问题的答案是现在iOS 4.0可以使用AVFoundation获取缩略图,下面的代码中class属性url是电影url,就可以了技巧(您可以随时获取缩略图,在示例中为时间 0)

The answer to this question is that one can now with 4.0 iOS get thumbnails using AVFoundation, the following code where the class property url is the movie url, will do the trick (you can get the thumbnail at any time, in the example its at time 0)

-(void)generateImage
{
    AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:self.url options:nil];
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    generator.appliesPreferredTrackTransform=TRUE;
    [asset release];
    CMTime thumbTime = CMTimeMakeWithSeconds(0,30);

    AVAssetImageGeneratorCompletionHandler handler = ^(CMTime requestedTime, CGImageRef im, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error){
        if (result != AVAssetImageGeneratorSucceeded) {
            NSLog(@"couldn't generate thumbnail, error:%@", error);
        }
        [button setImage:[UIImage imageWithCGImage:im] forState:UIControlStateNormal];
        thumbImg=[[UIImage imageWithCGImage:im] retain];
        [generator release];
    };

    CGSize maxSize = CGSizeMake(320, 180);
    generator.maximumSize = maxSize;
    [generator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:thumbTime]] completionHandler:handler];

}