你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> [iOS 相機相冊調用] UIImagePickerController 簡單實用 [轉]

[iOS 相機相冊調用] UIImagePickerController 簡單實用 [轉]

編輯:IOS開發綜合

在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 
#import 
#import 
@interface ViewController ()
{
    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 *)editingInfo {
    NSLog(@"選擇完畢----image:%@-----info:%@",image,editingInfo);
}
//適用獲取所有媒體資源,只需判斷資源類型
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)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 
#import 
#import 
@interface ComplaintViewController ()
{

    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 *)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
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved