coding with objc & swift

从视频中截图

| Comments

从视频中截图有两种方法,一种是用MPMoviePlayerController,另一种用AVAssetImageGenerator。请直接看代码。

第一种,用MPMoviePlayerController

1
2
3
4
5
6
7
8
9
10
+ (UIImage *)thumbnailFromVideoAtPath:(NSString *)videoFilePath
{
	NSURL *url = [NSURL fileURLWithPath:videoFilePath];
	MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:url];
	UIImage *image = [player thumbnailImageAtTime:2.0 timeOption:MPMovieTimeOptionNearestKeyFrame];
	[player stop];
	[player release];
	
	return image;
}

第二种,用AVAssetImageGenerator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
+ (UIImage *)thumbnailFromVideoAtPath:(NSString *)videoFilePath
{
    NSURL *url = [NSURL fileURLWithPath:videoFilePath];
    AVURLAsset *asset = [[[AVURLAsset alloc] initWithURL:url options:nil] autorelease];
    AVAssetImageGenerator *generator = [[[AVAssetImageGenerator alloc] initWithAsset:asset] autorelease];

    NSError *error = nil;
    CMTime time = CMTimeMakeWithSeconds(2.0, 60);
    CGImageRef imgRef = [generator copyCGImageAtTime:time actualTime:NULL error:&error];
    if (error.description != nil) NSLog(@"Error: (thumbnailFromVideoAtPath:)%@", error.description);
    UIImage *image = [[[UIImage alloc] initWithCGImage:imgRef] autorelease];
    CFRelease(imgRef);

    return image;
}

Comments