美文网首页iOS开发进阶iOS Developer
通视频URL截取第一帧图片

通视频URL截取第一帧图片

作者: 骑马纵天下 | 来源:发表于2017-06-21 19:51 被阅读283次

    为了方便直接给UIImage加个类别,以后什么时候使用可以直接调用。

    #import <UIKit/UIKit.h>
    
    @interface UIImage (Video)
    
    /**
     通过视频URL获取视频的第一帧图片
     
     @param videoURL 视频连接
     @return 第一帧图片
     */
    + (UIImage *)interceptFirstTimeVideoPicture:(NSURL *)videoURL;
    
    @end
    
    #import "UIImage+Video.h"
    #import <AVFoundation/AVFoundation.h>
    
    @implementation UIImage (Video)
    
    
    + (UIImage *)interceptFirstTimeVideoPicture:(NSURL *)videoURL{
        
        // 根据视频的URL创建AVURLAsset
        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
       
        // 根据AVURLAsset创建AVAssetImageGenerator对象
        AVAssetImageGenerator* gen = [[AVAssetImageGenerator alloc] initWithAsset: asset];
        
        gen.appliesPreferredTrackTransform = YES;
        
        // 定义获取0帧处的视频截图
        CMTime time = CMTimeMake(0, 10);
        
        NSError *error = nil;
        
        CMTime actualTime;
        
        // 获取time处的视频截图
        CGImageRef  image = [gen  copyCGImageAtTime: time actualTime: &actualTime error:&error];
        
        // 将CGImageRef转换为UIImage
        UIImage *thumb = [[UIImage alloc] initWithCGImage: image];
        
        CGImageRelease(image);
        
        return  thumb;
        
    }
    
    
    @end
    
    注意点:
    使用AVAssetImageGenerator这个类是要记得导入#import <AVFoundation/AVFoundation.h>头文件。
    
    image.png

    相关文章

      网友评论

        本文标题:通视频URL截取第一帧图片

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