美文网首页iOS技术专题iOS
iOS获取视频的封面图片

iOS获取视频的封面图片

作者: Mr_Jee | 来源:发表于2020-12-05 10:10 被阅读0次
    typedef void(^MyImageBlock)(UIImage * _Nullable image);
    
    异步获取视频的第一帧图片
    - (void)getThumbnailImage:(NSURL *)videoURL completion:(MyImageBlock)handler {
    
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
    
            AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
            
            AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
            
            generator.appliesPreferredTrackTransform = YES;
            
            CMTime time = CMTimeMakeWithSeconds(0.0, 600);
            
            NSError *error = nil;
            
            CMTime actualTime;
            
            CGImageRef imageRef = [generator copyCGImageAtTime:time actualTime:&actualTime error:&error];
            
            UIImage *thumb = [[UIImage alloc] initWithCGImage:imageRef];
            
            CGImageRelease(imageRef);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(thumb);
            });
        });
    }
    
    异步获取视频的任一帧图片
    - (void)getThumbnailImage:(NSURL *)videoURL atTime:(Float64)seconds completion:(MyImageBlock)handler {
    
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
    
            AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
            
            AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
            
            generator.appliesPreferredTrackTransform = YES;
            generator.requestedTimeToleranceBefore = kCMTimeZero;
            generator.requestedTimeToleranceAfter = kCMTimeZero;
            
            CMTime time = CMTimeMakeWithSeconds(seconds, 600);
            
            NSError *error = nil;
            
            CMTime actualTime;
            
            CGImageRef imageRef = [generator copyCGImageAtTime:time actualTime:&actualTime error:&error];
            
            UIImage *thumb = [[UIImage alloc] initWithCGImage:imageRef];
            
            CGImageRelease(imageRef);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(thumb);
            });
        });
    }
    

    相关文章

      网友评论

        本文标题:iOS获取视频的封面图片

        本文链接:https://www.haomeiwen.com/subject/cmowwktx.html