[转]iOS 应用中对视频进行抽帧的方法

You can do this in one of two ways. The first way is to use the MPMoviePlayerController to grab the thumbnail:

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

This works, but MPMoviePlayerController is not a particularly lightweight object and not particularly fast grabbing thumbnails.

The preferred way is to use the new AVAssetImageGenerator in AVFoundation. This is fast, lightweight and more flexible than the old way. Here's a helper method that will return an autoreleased image from the video.


+ (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
   
AVURLAsset *asset = [[[AVURLAsset alloc] initWithURL:videoURL options:nil] autorelease];
   
NSParameterAssert(asset);
   
AVAssetImageGenerator *assetImageGenerator = [[[AVAssetImageGenerator alloc] initWithAsset:asset] autorelease];
    assetImageGenerator
.appliesPreferredTrackTransform = YES;
    assetImageGenerator
.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;

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

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

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

   
return thumbnailImage;
}

posted @ 2012-04-18 22:46  Proteas  阅读(1370)  评论(0编辑  收藏  举报