2011-09-10 16 views
3

私は1つの画像からビデオを作成してそれを自分の写真ライブラリに保存しようとしています。私は年齢を超えて悩んでいます。iOS5 AVFoundation画像からビデオ

私はこのコードを持っている:私は、バックグラウンドスレッドでは、上記の方法

@autoreleasepool { 
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/movie2.mp4"]]; 

    UIImage *img = [UIImage imageWithData:[[self imageDataArrya]objectAtIndex:0]imageData]; 
    [self writeImageAsMovie:img toPath:path size:CGSizeMake(640, 960) duration:10]; 

    UISaveVideoAtPathToSavedPhotosAlbum (path,self, @selector(video:didFinishSavingWithError: contextInfo:), nil); 
} 

呼び出します。これは、「writeImageAsMovie」のコードです:

- (void)writeImageAsMovie:(UIImage*)image toPath:(NSString*)path size:(CGSize)size duration:(int)duration { 
NSError *error = nil; 
AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL: 
           [NSURL fileURLWithPath:path] fileType:AVFileTypeQuickTimeMovie 
                  error:&error]; 

NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys: 
           AVVideoCodecH264, AVVideoCodecKey, 
           [NSNumber numberWithInt:size.width], AVVideoWidthKey, 
           [NSNumber numberWithInt:size.height], AVVideoHeightKey, 
           nil]; 
[self setInput:[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo 
                outputSettings:videoSettings]]; 

AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor 
               assetWriterInputPixelBufferAdaptorWithAssetWriterInput:input 
               sourcePixelBufferAttributes:nil]; 

[videoWriter addInput:input]; 

[videoWriter startWriting]; 
[videoWriter startSessionAtSourceTime:kCMTimeZero]; 

CVPixelBufferRef buffer = [self pixelBufferFromCGImage:image.CGImage]; 
[adaptor appendPixelBuffer:buffer withPresentationTime:kCMTimeZero]; 
[adaptor appendPixelBuffer:buffer withPresentationTime:CMTimeMake(duration-1, 2)]; 

[input markAsFinished]; 
[videoWriter endSessionAtSourceTime:CMTimeMake(duration, 2)]; 
[videoWriter finishWriting]; 

}

CVPixelBufferRefに画像を変換するためのユーティリティメソッド:今、私はシミュレータからコードを実行しようとした場合

- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image { 
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: 
         [NSNumber numberWithBool:YES], kCVPixelBufferCGImageCompatibilityKey, 
         [NSNumber numberWithBool:YES], kCVPixelBufferCGBitmapContextCompatibilityKey, 
         nil]; 
CVPixelBufferRef pxbuffer = NULL; 

CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, 
             self.view.frame.size.width, 
             self.view.frame.size.height, 
             kCVPixelFormatType_32ARGB, 
             (__bridge CFDictionaryRef) options, 
             &pxbuffer); 

CVPixelBufferLockBaseAddress(pxbuffer, 0); 
void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer); 

CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB(); 
CGContextRef context = CGBitmapContextCreate(pxdata, self.view.frame.size.width, 
              self.view.frame.size.height, 8, 4*self.view.frame.size.width, rgbColorSpace, 
              kCGImageAlphaNoneSkipFirst); 
CGContextConcatCTM(context, CGAffineTransformMakeRotation(0)); 
CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image), 
             CGImageGetHeight(image)), image); 
CGColorSpaceRelease(rgbColorSpace); 
CGContextRelease(context); 

CVPixelBufferUnlockBaseAddress(pxbuffer, 0); 

return pxbuffer; 
} 

、それは私にデータが壊れていると言ってエラーを与える。

デバイス上で実行すると、2秒間のビデオがフォトライブラリに保存されますが、緑色の画像しか保存されません。

すべてのヘルプは理解されるであろう:)

+0

を。 – rckoenes

+0

oh ...:/私はこの質問を削除し、そこに尋ねるべきですか? –

+0

この回答はありましたか?私はまた、似たようなものに苦しんでいます。 – SayeedHussain

答えて

2

私は完全にこの作業を得た - 私は今日の前にお返事を見ていない申し訳ありません。 これは私が使用したものである:

一時ファイルを作成します

NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/flipimator-tempfile.mp4"]]; 

//overwrites it if it already exists. 
if([fileManager fileExistsAtPath:path]) 
    [fileManager removeItemAtPath:path error:NULL]; 

一時ファイルに画像を保存するには、エクスポート画像のメソッドを呼び出します。

[self exportImages:frames 
     asVideoToPath:path 
     withFrameSize:imageSize 
     framesPerSecond:fps]; 

一時保存写真アルバムへのファイル:

方法に

 - (void)exportImages:(NSArray *)imageArray 
      asVideoToPath:(NSString *)path 
      withFrameSize:(CGSize)imageSize 
     framesPerSecond:(NSUInteger)fps { 
     NSLog(@"Start building video from defined frames."); 

     NSError *error = nil; 

     AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL: 
             [NSURL fileURLWithPath:path] fileType:AVFileTypeQuickTimeMovie 
                    error:&error];  
     NSParameterAssert(videoWriter); 

     NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys: 
             AVVideoCodecH264, AVVideoCodecKey, 
             [NSNumber numberWithInt:imageSize.width], AVVideoWidthKey, 
             [NSNumber numberWithInt:imageSize.height], AVVideoHeightKey, 
             nil]; 

     AVAssetWriterInput* videoWriterInput = [AVAssetWriterInput 
               assetWriterInputWithMediaType:AVMediaTypeVideo 
               outputSettings:videoSettings]; 


     AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor 
                 assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput 
                 sourcePixelBufferAttributes:nil]; 

     NSParameterAssert(videoWriterInput); 
     NSParameterAssert([videoWriter canAddInput:videoWriterInput]); 
     videoWriterInput.expectsMediaDataInRealTime = YES; 
     [videoWriter addInput:videoWriterInput]; 

     //Start a session: 
     [videoWriter startWriting]; 
     [videoWriter startSessionAtSourceTime:kCMTimeZero]; 

     CVPixelBufferRef buffer = NULL; 

     //convert uiimage to CGImage. 
     int frameCount = 0; 

     for(UIImage * img in imageArray) { 
      buffer = [self pixelBufferFromCGImage:[img CGImage] andSize:imageSize]; 

      BOOL append_ok = NO; 
      int j = 0; 
      while (!append_ok && j < 30) { 
       if (adaptor.assetWriterInput.readyForMoreMediaData) { 
        //print out status:: 
        NSString *border = @"**************************************************"; 
        NSLog(@"\n%@\nProcessing video frame (%d,%d).\n%@",border,frameCount,[imageArray count],border); 

        CMTime frameTime = CMTimeMake(frameCount,(int32_t) fps); 
        append_ok = [adaptor appendPixelBuffer:buffer withPresentationTime:frameTime]; 
        if(!append_ok){ 
         NSError *error = videoWriter.error; 
         if(error!=nil) { 
          NSLog(@"Unresolved error %@,%@.", error, [error userInfo]); 
         } 
        } 

       } 
       else { 
        printf("adaptor not ready %d, %d\n", frameCount, j); 
        [NSThread sleepForTimeInterval:0.1]; 
       } 
       j++; 
      } 
      if (!append_ok) { 
       printf("error appending image %d times %d\n, with error.", frameCount, j); 
      } 
      frameCount++; 
     } 

     //Finish the session: 
     [videoWriterInput markAsFinished]; 
     [videoWriter finishWriting]; 
     NSLog(@"Write Ended"); 

    } 

Paramenters

  • imageArray:UIImageのNSArrayのexportImages方法10
    UISaveVideoAtPathToSavedPhotosAlbum (path,self, @selector(video:didFinishSavingWithError: contextInfo:), nil); 
    
    - (void)video:(NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo { 
        NSLog(@"Finished saving video with error: %@", error); 
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Done" 
                    message:@"Movie succesfully exported." 
                  delegate:nil 
               cancelButtonTitle:@"OK" 
               otherButtonTitles:nil, nil]; 
        [alert show]; 
    } 
    

    コード。

  • パス:処理中に書き込むための一時的なパス(上記で定義したtemp)。
  • imageSize:ビデオのサイズ(ピクセル単位)(幅と高さ)。
  • fps:1秒間に表示される画像の数。

希望します。 フォーマットについてごめんね.-私はまだStackOverflow.comを新しくしています。

私は、コードを使用する場所です:iOSの5はあなたがアップルの開発者フォーラムで、他の、それについて話すことは許されませんNDAの下にまだあるのでhttp://www.youtube.com/watch?v=DDckJyF2bnA

+0

こんにちは..このように私は歪んだ画像でビデオを取得しています。 –

関連する問題