2011-11-28 112 views
13

我正在使用UIImagePicker来允许用户创建视频并修剪它。我需要将该视频分成多个帧,并让用户选择其中一个。iOS将视频帧提取为图像

为了显示帧,我可能必须将它们转换为UIImage。我怎样才能做到这一点?我必须使用AVFoundation,但我找不到教程如何获取&转换帧。

我应该使用AVFoundation进行图像捕捉吗?如果是这样,我必须执行自己的修剪?

回答

6

这里是代码在viewDidLoad中

videoUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"VfE_html5" ofType:@"mp4"]]; 
    [self createImage:5]; // 5 is frame per second (FPS) you can change FPS as per your requirement. 
从视频获取FPS图像

1)导入

#import <Photos/Photos.h> 

2)

3)函数

-(void)createImage:(int)withFPS { 
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoUrl options:nil]; 
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset]; 
    generator.requestedTimeToleranceAfter = kCMTimeZero; 
    generator.requestedTimeToleranceBefore = kCMTimeZero; 

    for (Float64 i = 0; i < CMTimeGetSeconds(asset.duration) * withFPS ; i++){ 
     @autoreleasepool { 
      CMTime time = CMTimeMake(i, withFPS); 
      NSError *err; 
      CMTime actualTime; 
      CGImageRef image = [generator copyCGImageAtTime:time actualTime:&actualTime error:&err]; 
      UIImage *generatedImage = [[UIImage alloc] initWithCGImage:image]; 
      [self savePhotoToAlbum: generatedImage]; // Saves the image on document directory and not memory 
      CGImageRelease(image); 
     } 
    } 
} 

-(void)savePhotoToAlbum:(UIImage*)imageToSave { 

    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ 
     PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:imageToSave]; 
    } completionHandler:^(BOOL success, NSError *error) { 
     if (success) { 
      NSLog(@"sucess."); 
     } 
     else { 
      NSLog(@"fail."); 
     } 
    }]; 
}