相機相簿OC 詳解

William-logical發表於2016-11-08

這裡講的是 

使用UIImagePickerController的實現相機相簿的呼叫。需實現

UIImagePickerControllerDelegate,UINavigationControllerDelegate兩個協議。


基本實現步驟:

    1,初始化UIImagePickerController

     2,判斷裝置是否支援攝像或允許開啟相簿

     3,實現UIImagePickerController協議

      4,進行回撥


程式碼:

//

//  ViewController.m

//  相機相簿OC


//如果想要相簿 功能按鈕漢化 需在plist檔案中修改 Localization native development region  value的值為 China

#define Log(log) NSLog(@"Test:%@",log)

#define LLog(c,log) {NSString * str = [[NSString alloc] initWithFormat:@"%@",c];  NSLog(@"%@:%@",str,log);}


#import "ViewController.h"

#import "UIImagePickerController+Judge.h"

#import "AlertViewController.h"


#import <MobileCoreServices/MobileCoreServices.h>


@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>//UIImagePickerController需要實現的協議

///獲取圖片顯示

@property (weak, nonatomic) IBOutlet UIImageView *imageView;


///系統提供的用來獲取圖片和視訊的介面,執行UIImagePickerControllerDelegate,UINavigationControllerDelegate 兩個協議的回撥方法

@property (strong,nonatomicUIImagePickerController * pickerImage;


//判斷是選取相簿照片,還是相機拍照

@property BOOL isAlum;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    ////初始化UIImagePickerController

    self.pickerImage =[[UIImagePickerController alloc] init];


}

//開啟相機,需使用真機測試,否則會崩潰

- (IBAction)camera:(id)sender {

    ///代理判斷獲取資源型別

    self.isAlum = NO;

    

    //先設定sourceType

    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;

     ///設定資料來源型別,這裡設定為Camera

    self.pickerImage.sourceType = sourceType;

    //圖片允許編輯

    self.pickerImage.allowsEditing = YES;

    ///如果裝置不支援攝像頭 isAvailableCamera 封裝好的相機檢測,網上有很多,下同

    //  這裡返回的是 return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];

    if (![_pickerImage isAvailableCamera])

    {

        //提醒框

        [AlertViewController ViewController:self altetViewtitle:@"友情提示" Message:@"裝置未檢測到攝像頭" action:@"確定"];

    }else if ([_pickerImage isAvailableCamera] && [_pickerImage isSupportTaklingPhotos])////isSupportTaklingPhotos 檢測是否可以拍照。

    {//////如果有攝像頭,並且可以拍照

        //設定代理

         self.pickerImage.delegate = self;

        ///回撥

        [self presentViewController:_pickerImage animated:YES completion:nil];

    }else

    {

        ///提醒框

        [AlertViewController ViewController:self altetViewtitle:@"友情提示" Message:@"請在設定中開啟相機許可權" action:@"確定"];

    }

}

//開啟相簿

- (IBAction)album:(id)sender {

    self.isAlum = YES;

    

       /*

     *資料來源有三種:

     * 1 UIImagePickerControllerSourceTypePhotoLibrary, ---來自相簿

     * 2 UIImagePickerControllerSourceTypeCamera,   ---來自相機

     * 3 UIImagePickerControllerSourceTypeSavedPhotosAlbum  ----來自相簿

     */

    ///設定資料來源型別,這裡設定為photo library

    self.pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

    ///協議

    self.pickerImage.delegate = self;

    //圖片允許編輯

    self.pickerImage.allowsEditing = YES;

    

     /*

      *檢測相簿是否可用,即是否存在資料來源

      */

    if ([_pickerImage isAvailablePhotoLibrary])

    {

        ///回撥

        [self presentViewController:_pickerImage animated:YES completion:nil];

    }else

    {

        

        [AlertViewController ViewController:self altetViewtitle:@"友情提示" Message:@"相簿不可用" action:@"確定"];

    }


}



#pragma mark-協議

///使用者選取完成後呼叫

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

    /* 使用者選取的資訊都在info

     *info裡的鍵值如下:

     * NSString *const  UIImagePickerControllerMediaType ;指定使用者選擇的媒體型別(如下:)

     * NSString *const  UIImagePickerControllerOriginalImage ;原始圖片

     * NSString *const  UIImagePickerControllerEditedImage ;修改後的圖片

     * NSString *const  UIImagePickerControllerCropRect ;裁剪尺寸

     * NSString *const  UIImagePickerControllerMediaURL ;媒體的URL

     * NSString *const  UIImagePickerControllerReferenceURL ;原件的URL

     * NSString *const  UIImagePickerControllerMediaMetadata;當來資料來源是照相機的時候這個值才有效

     */

    /*指定使用者選擇的媒體型別

     *UIImagePickerControllerMediaType 包含著KUTTypeImage KUTTypeMovie

     說明:使用指定媒體型別 需包含  <MobileCoreServices/MobileCoreServices.h>

     

     KUTTypeImage 包含:

     const CFStringRef  kUTTypeImage ;抽象的圖片型別

     const CFStringRef  kUTTypeJPEG ;

     const CFStringRef  kUTTypeJPEG2000 ;

     const CFStringRef  kUTTypeTIFF ;

     const CFStringRef  kUTTypePICT ;

     const CFStringRef  kUTTypeGIF ;

     const CFStringRef  kUTTypePNG ;

     const CFStringRef  kUTTypeQuickTimeImage ;

     const CFStringRef  kUTTypeAppleICNS

     const CFStringRef kUTTypeBMP;

     const CFStringRef  kUTTypeICO;

     

     KUTTypeMovie 包含:

     const CFStringRef  kUTTypeAudiovisualContent ;抽象的聲音視訊

     const CFStringRef  kUTTypeMovie ;抽象的媒體格式(聲音和視訊)

     const CFStringRef  kUTTypeVideo ;只有視訊沒有聲音

     const CFStringRef  kUTTypeAudio ;只有聲音沒有視訊

     const CFStringRef  kUTTypeQuickTimeMovie ;

     const CFStringRef  kUTTypeMPEG ;

     const CFStringRef  kUTTypeMPEG4 ;

     const CFStringRef  kUTTypeMP3 ;

     const CFStringRef  kUTTypeMPEG4Audio ;

     const CFStringRef  kUTTypeAppleProtectedMPEG4Audio;

     */

    ////獲取資料型別

    NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];

    ///如果是圖片型別

    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {

        //如果是相簿選擇圖片,否則是拍照

        if (_isAlum) {

            //相簿選擇

            [self chosePhoto:picker WithInfo:info];

        }else{

            ///拍照

            [self savePhoto:picker WithInfo:info];

 

        }

    }else{

        

    }

    

    

    


}

//使用者取消選取時呼叫

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

    

    [picker dismissViewControllerAnimated:YES completion:nil];

}



///拍照儲存

-(void)savePhoto:(UIImagePickerController*)picker WithInfo:(NSDictionary<NSString *,id> *)info{

    ////是否儲存成功

    SEL select = @selector(imageWasSavedSuccessfully: didFinishSavingWithError: contextInfo:);

    

    ///選擇相片後移除相簿

    [picker dismissViewControllerAnimated:YES completion:^{

        

        UIImage * image;

        

        //如果允許被編輯,獲取編輯後的圖片,否則獲取原始圖片

        if (picker.allowsEditing) {

            ///編輯後的圖片

            image = [info objectForKey:UIImagePickerControllerEditedImage];

        }else{

            //原始圖片

            image = [info objectForKey:UIImagePickerControllerOriginalImage];

        }

        //顯示圖片

        self.imageView.image = image;

        

        /*

         *非同步儲存圖片

         */

        ////分組

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

        

        ///非同步執行

        dispatch_async(queue, ^{

            dispatch_group_t group = dispatch_group_create();

            ///非同步

            dispatch_group_async(group, queue, ^{

                

                /////儲存到系統相簿中·

                UIImageWriteToSavedPhotosAlbum(image, self, select, NULL);

            });

            

        });

        

        

    }];

}

///選擇照片

-(void)chosePhoto:(UIImagePickerController*)picker WithInfo:(NSDictionary<NSString *,id> *)info{

   

    

    ///選擇相片後移除相簿

    [picker dismissViewControllerAnimated:YES completion:^{

        ///顯示圖片

        [self getImage:picker Info:info];

        

    }];

}

/////顯示獲取選取後的圖片

-(void)getImage:(UIImagePickerController*)picker Info:(NSDictionary<NSString *,id> *)info{

    UIImage * image;

    //如果允許被編輯,獲取編輯後的圖片,否則獲取原始圖片

    if (picker.allowsEditing) {

        ///編輯後的圖片

        image = [info objectForKey:UIImagePickerControllerEditedImage];

    }else{

        //原始圖片

        image = [info objectForKey:UIImagePickerControllerOriginalImage];

    }

    //顯示圖片

    self.imageView.image = image;


}

// 儲存圖片到相簿後,呼叫的相關方法,檢視是否儲存成功

- (void)imageWasSavedSuccessfully:(UIImage *)paramImage didFinishSavingWithError:(NSError *)paramError contextInfo:(void *)paramContextInfo{

    if (paramError == nil){

        Log(@"Image was saved successfully.");

    } else {

        Log(@"An error happened while saving the image.");

        LLog(@"Error = %@", paramError);

    }

}

@end


效果圖:

Demo: 點我下載Demo


相關文章