iOS 获取视频第一帧的图片

//方法 1

- (UIImage*)firstFrameWithVideoURL:(NSURL*)url size:(CGSize)size{

    // 获取视频第一帧

    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];

    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];

    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];

    generator.appliesPreferredTrackTransform = YES;

    generator.maximumSize = CGSizeMake(size.width, size.height);

    NSError*error =nil;

    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];

    {

        return [UIImage imageWithCGImage:img];

    }

    return nil;

}

//方法 2

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:@"http://117.50.29.11:8888/qhzf/bimQHZFile/uploadFile/question/2018-10-17/8a9182a7661a018b01667fdcdbfe0057.mp4"] options:nil];

        NSParameterAssert(asset);

        AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];

        assetImageGenerator.appliesPreferredTrackTransform=YES;

        assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;

        CGImageRefthumbnailImageRef =NULL;

        CFTimeIntervalthumbnailImageTime =1;

        NSError*thumbnailImageGenerationError =nil;

        thumbnailImageRef = [assetImageGeneratorcopyCGImageAtTime:CMTimeMake(thumbnailImageTime,60)actualTime:NULLerror:&thumbnailImageGenerationError];

        if(!thumbnailImageRef)

            NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);

        UIImage*thumbnailImage = thumbnailImageRef ? [[UIImagealloc]initWithCGImage: thumbnailImageRef] :nil;

//回到主线程 给imageV赋值

        dispatch_async(dispatch_get_main_queue(), ^{

            UIImageView*imageView = [[UIImageViewalloc]initWithImage:thumbnailImage];

            imageView.center=CGPointMake(100,100);

            [self.viewaddSubview:imageView];

        });

       NSLog(@"image%@",thumbnailImage);


    });

你可能感兴趣的:(iOS 获取视频第一帧的图片)