UIImagePickerController從拍照、圖庫(kù)手幢、相冊(cè)獲取圖片

`好吧,還是沒(méi)出原型圖,把頭像上傳的代碼整理一下,方便大家理解,這個(gè)是最常用最基本的功能了吧

iOS獲取圖片有三種方式:

  • 直接調(diào)用攝像頭拍照
  • 從相冊(cè)中選擇
  • 從圖庫(kù)中選擇(其實(shí)圖庫(kù)里包含著相冊(cè),所以一般只用兩種)

系統(tǒng)提供了UIImagePickerController用來(lái)獲取圖片和視頻的接口
使用步驟如下

  1. 初始化UIImagePickerController
  2. 設(shè)置UIImagePickerController的數(shù)據(jù)源類(lèi)型
  3. 設(shè)置代理,遵循UIImagePickerControllerDelegate,UINavigationControllerDelegate協(xié)議
  4. 接收代理,存儲(chǔ)圖片

圖片來(lái)源為三種

typedef NS_ENUM(NSInteger, UIImagePickerControllerSourceType) {
    UIImagePickerControllerSourceTypePhotoLibrary, // 圖集
    UIImagePickerControllerSourceTypeCamera, // 相機(jī)
    UIImagePickerControllerSourceTypeSavedPhotosAlbum // 相冊(cè)
} __TVOS_PROHIBITED;

注意的是需要判定設(shè)備是否支持

if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        NSLog(@"支持相機(jī)");
    }
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        NSLog(@"支持圖庫(kù)");
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
    {
        NSLog(@"支持相片庫(kù)");
    }

好了,寫(xiě)了個(gè)小Demo,直接上代碼了

#import "ViewController.h"

@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

/** imageView */
@property (nonatomic, strong) UIImageView *imageView;

/** imageViewR */
@property (nonatomic, strong) UIImageView *imageViewR;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.imageViewR = [[UIImageView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 100)/2, 30, 100, 100)];
    self.imageViewR.backgroundColor = [UIColor grayColor];
    self.imageViewR.layer.cornerRadius = 50;
    self.imageViewR.layer.masksToBounds = YES; // 裁剪邊
    [self.view addSubview:self.imageViewR];
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(16, 140, self.view.frame.size.width - 32, self.view.frame.size.width - 32)];
    self.imageView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.imageView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(16, CGRectGetMaxY(self.imageView.frame) + 20, self.view.frame.size.width - 32, 35);
    btn.backgroundColor = [UIColor greenColor];
    btn.layer.cornerRadius = 5;
    btn.layer.masksToBounds = YES;
    [btn setTitle:@"獲取圖片" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

- (void)btnClick:(UIButton *)button
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"選擇照片" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    // 判斷是否支持相機(jī)
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIAlertAction *cameraAc = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = YES;
            // 設(shè)置數(shù)據(jù)源類(lèi)型
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertController addAction:cameraAc];
    }
    // 圖集
    UIAlertAction *photoAc = [UIAlertAction actionWithTitle:@"相冊(cè)" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    [alertController addAction:photoAc];
    
    // 相片庫(kù)
    UIAlertAction *albumAc = [UIAlertAction actionWithTitle:@"相片庫(kù)" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    [alertController addAction:albumAc];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:cancel];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 代理方法,獲取圖片
// 選取的信息都在info中捷凄,info 是一個(gè)字典。
/**
// info dictionary keys
UIKIT_EXTERN NSString *const UIImagePickerControllerMediaType __TVOS_PROHIBITED;      // an NSString (UTI, i.e. kUTTypeImage)
UIKIT_EXTERN NSString *const UIImagePickerControllerOriginalImage __TVOS_PROHIBITED;  // a UIImage
UIKIT_EXTERN NSString *const UIImagePickerControllerEditedImage __TVOS_PROHIBITED;    // a UIImage
UIKIT_EXTERN NSString *const UIImagePickerControllerCropRect __TVOS_PROHIBITED;       // an NSValue (CGRect)
UIKIT_EXTERN NSString *const UIImagePickerControllerMediaURL __TVOS_PROHIBITED;       // an NSURL
UIKIT_EXTERN NSString *const UIImagePickerControllerReferenceURL        NS_AVAILABLE_IOS(4_1) __TVOS_PROHIBITED;  // an NSURL that references an asset in the AssetsLibrary framework
UIKIT_EXTERN NSString *const UIImagePickerControllerMediaMetadata       NS_AVAILABLE_IOS(4_1) __TVOS_PROHIBITED;  // an NSDictionary containing metadata from a captured photo
UIKIT_EXTERN NSString *const UIImagePickerControllerLivePhoto NS_AVAILABLE_IOS(9_1) __TVOS_PROHIBITED;  // a PHLivePhoto
/
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    // 保存圖片到本地沙盒,
    [self saveImage:image withName:@"avatar.png"];
    
    NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"avatar.png"];
    UIImage *saveImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    
    // 設(shè)置圖片顯示
    self.imageView.image = saveImage;
    self.imageViewR.image = saveImage;
}

- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1); // 1為不縮放保存,取值為(0~1)
    
    // 獲取沙河路徑
    NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:imageName];
    // 將照片寫(xiě)入文件
    [imageData writeToFile:fullPath atomically:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末围来,一起剝皮案震驚了整個(gè)濱河市跺涤,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌监透,老刑警劉巖桶错,帶你破解...
    沈念sama閱讀 212,816評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異胀蛮,居然都是意外死亡院刁,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,729評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén)醇滥,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)黎比,“玉大人,你說(shuō)我怎么就攤上這事鸳玩≡某妫” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 158,300評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵不跟,是天一觀的道長(zhǎng)颓帝。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么购城? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,780評(píng)論 1 285
  • 正文 為了忘掉前任吕座,我火速辦了婚禮,結(jié)果婚禮上瘪板,老公的妹妹穿的比我還像新娘吴趴。我一直安慰自己,他們只是感情好侮攀,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,890評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布锣枝。 她就那樣靜靜地躺著,像睡著了一般兰英。 火紅的嫁衣襯著肌膚如雪撇叁。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 50,084評(píng)論 1 291
  • 那天畦贸,我揣著相機(jī)與錄音陨闹,去河邊找鬼。 笑死薄坏,一個(gè)胖子當(dāng)著我的面吹牛趋厉,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播颤殴,決...
    沈念sama閱讀 39,151評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼觅廓,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了涵但?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,912評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤帖蔓,失蹤者是張志新(化名)和其女友劉穎矮瘟,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體塑娇,經(jīng)...
    沈念sama閱讀 44,355評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡澈侠,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,666評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了埋酬。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片哨啃。...
    茶點(diǎn)故事閱讀 38,809評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖写妥,靈堂內(nèi)的尸體忽然破棺而出拳球,到底是詐尸還是另有隱情,我是刑警寧澤珍特,帶...
    沈念sama閱讀 34,504評(píng)論 4 334
  • 正文 年R本政府宣布祝峻,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏莱找。R本人自食惡果不足惜酬姆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,150評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望奥溺。 院中可真熱鬧辞色,春花似錦、人聲如沸浮定。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,882評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)壶唤。三九已至雳灵,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間闸盔,已是汗流浹背悯辙。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,121評(píng)論 1 267
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留迎吵,地道東北人躲撰。 一個(gè)月前我還...
    沈念sama閱讀 46,628評(píng)論 2 362
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像击费,于是被迫代替她去往敵國(guó)和親拢蛋。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,724評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容