動画からサムネイル画像を生成する

( iOS )

動画のある一部分を画像として取り出したいときがあったので調べてみたら、ドキュメントにそれっぽい記述があったので実装してみました。

方法としては、以下のメソッドを利用してCMTimeを利用して指定された時間に対する画像を生成します。

copyCGImageAtTime:actualTime:error:

実際に、メソッドにして動くようにしました。

- (UIImage*)createThumbnailImageWithURL:(NSURL *)movieURL
{
    AVAsset *asset = [[AVURLAsset alloc] initWithURL:[movieURL objectAtIndex:index] options:nil];

    if ([asset tracksWithMediaCharacteristic:AVMediaTypeVideo]) {
        AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];

        Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
        CMTime midpoint         = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
        NSError* error          = nil;
        CMTime actualTime;

        CGImageRef halfWayImageRef = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];

        if (halfWayImageRef != NULL) {
            UIImage* image = [[UIImage alloc]initWithCGImage:halfWayImageRef];

            // 明示的にリリースしておきます
            CGImageRelease(halfWayImageRef);
            return image;
        }
    }
    return nil;
}

動画を取り終わった後に、一時的に一覧として残しておきたいときなどに利用できますね。

p.s.

これは試していないのですが、以下のメソッドがあってブロックの中で複数の画像が生成できるようです。

generateCGImagesAsynchronouslyForTimes:completionHandler::^(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error)

ref