[iOS 相机相册调用] UIImagePickerController 简单实用 [转]

##[转]
文/Shelin(简书作者)
原文链接:http://www.jianshu.com/p/e70a184d1f32
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。**

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

使用UIImagePickerController拍照或者拍视频主要以下几个步骤:
创建一个全局的UIImagePickerController对象。
指定UIImagePickerController的来源sourceType,是来自UIImagePickerControllerSourceTypeCamera相机,还是来自UIImagePickerControllerSourceTypePhotoLibrary相册。
然后是设置mediaTypes媒体类型,这是录制视频必须设置的选项,默认情况下是kUTTypeImage(注意:mediaTypes的设置是在MobileCoreServices框架下),同还可以设置一些其他视频相关的属性,例如:videoQuality视频的质量、videoMaximumDuration视频的最大录制时长(默认为10s),cameraDevice摄像头的方向(默认为后置相机)。
指定相机的捕获模式cameraCaptureMode,设置mediaTypes后在设置捕获模式,注意的是捕获模式需要在相机来源sourceType为相机时设置,否则会出现crash。

适时的展示UIImagePickerController,然后在相应的代理方法保存和获取图片或视频。

下面还是上代码吧,更加清晰明了…
首先需要导入以下用到的几个头文件,同时遵守两个代理方法

#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;
    [self presentViewController:_imagePickerController animated:YES completion:nil];
}

从相册获取图片或视频

#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];
}

图片和视频保存完毕后的回调

#pragma mark 图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{

}

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

以上仅是简单功能的实现,还有例如切换前后摄像头、闪光灯设置、对焦、曝光模式等更多功能…


##以下为自己的应用 仅供自己翻阅

//
//  ComplaintViewController.m
//  QuickPos
//
//  Created by Lff on 16/8/1.
//  Copyright © 2016年 张倡榕. All rights reserved.
//

#import "ComplaintViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
@interface ComplaintViewController ()<ResponseData,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    
    NSMutableArray  *_dataArray;
    Request *_rep;
    UIImagePickerController *_imagePickerController;
}
@property (weak, nonatomic) IBOutlet UIView *BGview1;//模块1
@property (weak, nonatomic) IBOutlet UIView *BGview2;
@property (weak, nonatomic) IBOutlet UIView *BGview3;


@property (weak, nonatomic) IBOutlet UITextField *nameProduct;
@property (weak, nonatomic) IBOutlet UITextField *sizeProduct;
@property (weak, nonatomic) IBOutlet UITextField *dateProduct;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *mobile;
@property (weak, nonatomic) IBOutlet UITextField *email;
@property (weak, nonatomic) IBOutlet UITextField *address;
@property (weak, nonatomic) IBOutlet UILabel *photoLab;
@property (weak, nonatomic) IBOutlet UIImageView *photoImageShoew;

@end

@implementation ComplaintViewController
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    self.navigationController.navigationBar.x = 0;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"投诉建议";
    self.view.backgroundColor = [Common hexStringToColor:@"eeeeee"];
    _rep = [[Request alloc] initWithDelegate:self];

    [self setImagePickerController];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setImagePickerController{
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate  = self;
    _imagePickerController.allowsEditing = YES;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;

}

//相机/相册
- (IBAction)cameraGetBtn:(id)sender {

    [Common pstaAlertWithTitle:@"提示" message:@"请选择图片来源方式" defaultTitle:@"相册" cancleTitle:@"相机" defaultBlock:^(id defaultBlock) {
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:_imagePickerController animated:YES completion:nil];

    } CancleBlock:^(id cancleBlock) {
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        _imagePickerController.videoMaximumDuration = 10;
        _imagePickerController.mediaTypes = @[(NSString*)kUTTypeMovie,(NSString*)kUTTypeImage];
        _imagePickerController.videoQuality = UIImagePickerControllerQualityTypeLow;
        _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        [self presentViewController:_imagePickerController animated:YES completion:nil];

           } ctr:self];

}

#pragma  mark - imagePickerControllerDelegate
//适用获取所有媒体资源,只需判断资源类型
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    NSString *mdeiaTye = [info objectForKey:UIImagePickerControllerMediaType]; //获取媒体类型
    if ([mdeiaTye isEqualToString:(NSString*)kUTTypeImage]) {  //判断媒体类型是图片
        UIImage *image = info[UIImagePickerControllerEditedImage];
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        NSString *iamgeStrBase64 = [data base64Encoding];
        NSLog(@"%@,%lu",iamgeStrBase64,iamgeStrBase64.length/1024);
        
        _photoLab.text = @"照片已选择";
        _photoImageShoew.image = image;

        
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

//提交
- (IBAction)upDateBtn:(id)sender {
    [_rep postComplaintWithtagId:@"F1060F560C2002E0" tagSn:@"000000000777" tagSnProducerCode:@"SHFDA" enterpriseId:@"3" productId:@"47" userName:@"INESA芥花油" mobile:@"15151474388" comments:@"123"];
    
    [Common pstaAlertWithTitle:@"" message:@"已提交" defaultTitle:@"留在本页" cancleTitle:@"返回主页" defaultBlock:^(id defaultBlock) {
        NSLog(@"123");
        
    } CancleBlock:^(id cancleBlock) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    } ctr:self];
    
    
    
}
-(void)responseWithDict:(NSDictionary *)dict requestType:(NSInteger)type{
    if (type == REQUSET_Complaint) {
        
        
    }
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
//    _photoImageShoew.ima

    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值