美文网首页
iOS拍照和录制视频实现

iOS拍照和录制视频实现

作者: xiaofu666 | 来源:发表于2022-02-23 12:31 被阅读0次

在iOS中要拍照和录制视频最简单的方式就是调用UIImagePickerControllerUIImagePickerController继承与UINavigationController,需要使用代理方法时需要同时遵守这两个协议,以前可能比较多的是使用UIImagePickerController来选择相册图片或者拍摄图片,其实它的功能还能用来拍摄视频。

使用UIImagePickerController拍照或者拍视频主要以下几个步骤:

创建一个全局的UIImagePickerController对象。

指定UIImagePickerController的来源sourceType,是来自UIImagePickerControllerSourceTypeCamera相机,还是来自UIImagePickerControllerSourceTypePhotoLibrary相册。

然后是设置mediaTypes媒体类型,这是录制视频必须设置的选项,默认情况下是kUTTypeImage(注意:mediaTypes的设置是在MobileCoreServices框架下),同时还可以设置一些其他视频相关的属性,例如:videoQuality视频的质量、videoMaximumDuration视频的最大录制时长(默认为10s),cameraDevice摄像头的方向(默认为后置相机)。

指定相机的捕获模式cameraCaptureMode,设置mediaTypes后在设置捕获模式!

注意 : 捕获模式需要在来源sourceType为相机时设置,否则会出现crash。

示例代码如下:
首先需要导入以下用到的几个头文件,同时遵守两个代理方法

#import "ViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@interface ViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    UIImagePickerController *_imagePickerController;
}

创建UIImagePickerController对象

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib
   
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
}   

从摄像头获取图片或视频

#pragma mark 从摄像头获取图片或视频
- (void)selectImageFromCamera
{
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    //录制视频时长,默认10s
    _imagePickerController.videoMaximumDuration = 15;

    //相机类型(拍照、录像...)字符串需要做相应的类型转换
    _imagePickerController.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];

    //视频上传质量
    //UIImagePickerControllerQualityTypeHigh高清
    //UIImagePickerControllerQualityTypeMedium中等质量
    //UIImagePickerControllerQualityTypeLow低质量
    //UIImagePickerControllerQualityType640x480
    _imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;

    //设置摄像头模式(拍照,录制视频)为录像模式
    _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;

    // 是否编辑拍完的图片
    _imagePickerController.allowsEditing = NO;
    // 仅当 sourceType 为 UIImagePickerControllerSourceTypeCamera 时,相机添加才可用。
   //  _imagePickerController.showsCameraControls = YES;//可设置一个视图来覆盖预览视图
   //  _imagePickerController.cameraOverlayView = nil;//可设置一个视图来覆盖预览视图

    // UIImagePickerControllerCameraCaptureModePhoto
    // UIImagePickerControllerCameraCaptureModeVideo
    _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;

    // UIImagePickerControllerCameraDeviceRear  //后摄像头
    // UIImagePickerControllerCameraDeviceFront //前摄像头
    _imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;

    // cameraFlashMode 控制当 cameraCaptureMode 为 Photo 时的静止图像闪光。 当 cameraCaptureMode 为 Video 时,cameraFlashMode 控制视频手电筒。
    // UIImagePickerControllerCameraFlashModeOff  = -1,
    // UIImagePickerControllerCameraFlashModeAuto = 0,
    // UIImagePickerControllerCameraFlashModeOn   = 1
    _imagePickerController.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
    

    [self presentViewController:_imagePickerController animated:YES completion:nil];
}

方法说明

    [_imagePickerController takePicture];// 拍照
    [_imagePickerController startVideoCapture];// 开始录像
    [_imagePickerController stopVideoCapture]; // 停止录像

从相册获取图片或视频

#pragma mark 从相册获取图片或视频
- (void)selectImageFromAlbum
{
    //NSLog(@"相册");
    _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:_imagePickerController animated:YES completion:nil];
}

在imagePickerController:didFinishPickingMediaWithInfo:代理方法中处理得到的资源,保存本地并上传...

#pragma mark UIImagePickerControllerDelegate
//该代理方法仅适用于只选取图片时
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo {
    NSLog(@"选择完毕----image:%@-----info:%@",image,editingInfo);
}
//适用获取所有媒体资源,只需判断资源类型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    //判断资源类型
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
        //如果是图片
        self.imageView.image = info[UIImagePickerControllerEditedImage];
        //压缩图片
        NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
        //保存图片至相册
        UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        //上传图片
        [self uploadImageWithData:fileData];
        
    }else{
        //如果是视频
        NSURL *url = info[UIImagePickerControllerMediaURL];
        //播放视频
        _moviePlayer.contentURL = url;
        [_moviePlayer play];
        //保存视频至相册(异步线程)
        NSString *urlStr = [url path];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
                
                UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
            }
        });
        NSData *videoData = [NSData dataWithContentsOfURL:url];
        //视频上传
        [self uploadVideoWithData:videoData];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

图片和视频保存回调

// 图片保存
// UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
#pragma mark 图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{
    if (error) {
        NSLog(@"保存图片过程中发生错误,错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"图片保存成功.");
    }
}
// 视频保存
// UISaveVideoAtPathToSavedPhotosAlbum(@"videoPath", self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
#pragma mark 视频保存完毕的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
    if (error) {
        NSLog(@"保存视频过程中发生错误,错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"视频保存成功.");
    }
}

相关文章

网友评论

      本文标题:iOS拍照和录制视频实现

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