iOS 通过视频URL或者filePath 获取第一帧图片

1. 网络URL

+ (UIImage*)getThumbnailImage:(NSString*)videoURL{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:videoURL] options:nil];

    NSParameterAssert(asset);//断言

    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;

    NSTimeInterval time = 0.1;
    CGImageRefthumbnailImageRef =NULL;
    CFTimeIntervalthumbnailImageTime = time;
    NSError*error =nil;
    thumbnailImageRef = [assetImageGeneratorcopyCGImageAtTime:CMTimeMake(thumbnailImageTime,60)actualTime:NULLerror:&error];

    if( error ) {
        NSLog(@"%@", error );
    }

    if( thumbnailImageRef ) {
        return[[UIImagealloc]initWithCGImage:thumbnailImageRef];
    }

    return nil;

}
  1. AVAssetImageGeneratorApertureModeCleanAperture
  en:An image's clean aperture is a region of video free from transition artifacts caused by the encoding of the signal.
  desc: 图像的干净光圈是一个没有信号编码引起的过渡伪影的视频区域
  2. AVAssetImageGeneratorApertureModeProductionAperture
  en:The image is not cropped to the clean aperture region, but it is scaled according to the pixel aspect ratio. Use this option when you want to see all the pixels in your video, including the edges.
  desc: 图像不会被裁剪到干净的光圈区域,但会根据像素长宽比进行缩放。如果您想要查看视频中的所有像素(包括边缘),请使用此选项。
  3. AVAssetImageGeneratorApertureModeEncodedPixels
  en: The image is not cropped to the clean aperture region and is not scaled according to the pixel aspect ratio. The encoded dimensions of the image description are displayed.
  desc: 图像不会被裁剪到干净的光圈区域,也不会根据像素长宽比进行缩放。显示图像说明的编码尺寸。

有没有大佬给解释下上面三个的具体意思以及区别是什么,拜谢!

其实主要就是AVAssetImageGenerator 这个类,有其他需求研究这个类,非常有用,因为产品需求只是第一帧,所以时间是0.1,可以根据自己需求设置

2. 本地URL

+ (UIImage *)xy_getVideoThumbnail:(NSString *)filePath
{
    NSURL *sourceURL = [NSURL fileURLWithPath:filePath];
    AVAsset *asset = [AVAsset assetWithURL:sourceURL];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMake(0, 1);
    NSError *error;
    CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:&error];
    UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);  // CGImageRef won't be released by ARC
    return thumbnail;
}

你可能感兴趣的:(iOS 通过视频URL或者filePath 获取第一帧图片)