iOS获取视频缩略图

首先需要导入AVFoundation库。

UIImagePickerController

调用摄像头拍照,摄像的时候需要用到UIImagePickerController。
使用方法:

    //实例化一个对象
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;//设置照片源类型
    imagePicker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//设置媒体种类
    imagePicker.allowsEditing = NO; //允许编辑
    imagePicker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;//闪光灯模式
    imagePicker.cameraDevice = UIImagePickerControllerCameraDeviceRear;//摄像头前置还是后置
    imagePicker.delegate = self;//设置代理
    //通过模态视图推出页面
    [self presentViewController:imagePicker animated:YES completion:nil];

sourceType 的三种类型分别是:
UIImagePickerControllerSourceTypeCamera 照相机
UIImagePickerControllerSourceTypePhotoLibrary 照片库 (用户不可删除)
UIImagePickerControllerSourceTypeSavedPhotosAlbum 通过摄像头保存的照片(用户可删除)

如果需要对拍摄的照片或视频进行保存,需要给设置代理,然后遵守两个协议 ,实现下面的代理方法:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info;

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker;

通常情况下,在didFinish方法里面对照片或视频进行保存处理;在didCancel方法里dismissViewController。

获取视频缩略图

这里我用的filePath是本地视频的存储路径;网络视频URL同理。

/**
 *  获取视频的缩略图方法
 *
 *  @param filePath 视频的本地路径
 *
 *  @return 视频截图
 */
- (UIImage *)getScreenShotImageFromVideoPath:(NSString *)filePath{
    
    UIImage *shotImage;
    //视频路径URL
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];
    
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    gen.appliesPreferredTrackTransform = YES;
    
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    
    NSError *error = nil;
    
    CMTime actualTime;
    
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    
    shotImage = [[UIImage alloc] initWithCGImage:image];
    
    CGImageRelease(image);
    
    return shotImage;
    
}

参考源码

你可能感兴趣的:(iOS获取视频缩略图)