iOS截取視頻某一幀圖片(關鍵幀,AVAssetImageGenerator)


獲取第一幀圖片

導入 AVFoundation.Framework、CoreMedia.Framework

實現代碼例如以下:

+ (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; }


獲取多幀圖片的辦法

[mImageGenerator generateCGImagesAsynchronouslyForTimes:[NSArray arrayWithObject:[NSValue valueWithCMTime:CMTimeMakeWithSeconds(time, NSEC_PER_SEC)]] completionHandler:
    ^(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error)
    {
 
        NSLog(@"actual got image at time:%f", CMTimeGetSeconds(actualTime));
        if (image)
        {
            [CATransaction begin];
            [CATransaction setDisableActions:YES];
            [layer setContents:(id)image];
 
            //UIImage *img = [UIImage imageWithCGImage:image];
            //UIImageWriteToSavedPhotosAlbum(img, self, nil, nil);
 
            [CATransaction commit];
        }
    }];
 



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM