2011-11-28 156 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."); 
     } 
    }]; 
}