iOS——调用系统相册和相机

UIImagePickerController

调用相册需要用到UIImagePickerController,这是iOS系统提供的和系统的相册和相机交互的一个类,可以用来获取相册的照片,也可以调用系统的相机拍摄照片或者视频。该类的继承结构是:

UIImagePickerController-->UINavigationController-->UIViewController-->UIResponder-->NSObject

调用相册:

  • 首先需要导入对应的库和声明相关的属性:
objectivec 复制代码
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h>


@interface ViewController : UIViewController<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIImagePickerController *imagePicker;

@end
  • 获取相册信息:
objectivec 复制代码
//点击按钮执行调用手机相册的事件
- (void) selectPhoto {
    //检查当前设备是否支持使用相册作为照片的源
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        //创建UIImagePickerController实例对象
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        //设置照片的源为相册
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //设置允许用户对照片进行编辑、即用户可以对照片进行裁剪、旋转等操作
        picker.allowsEditing = YES;
        //设置picker的代理
        picker.delegate = self;
        //退出picker模态视图
        [self presentViewController:picker animated:YES completion:nil];
    } else {
        NSLog(@"照片源不可用");
    }
}
objectivec 复制代码
// UIImagePickerControllerDelegate的协议方法,用于在用户选择媒体(照片或视频)后进行回调,其中info是用户选择的媒体的信息的字典,字典中的键是枚举值UIImagePickerControllerInfoKey,它定义了一系列用于访问 info 字典中特定信息的键
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    //从info字典中获取编辑后的图片。UIImagePickerControllerEditedImage是一个键,表示用户在相册中选择照片并进行了编辑的情况下获取的照片,如果用户没有编辑,就使用UIImagePickerControllerOriginalImage获取原始图片
    UIImage *image = info[@"UIImagePickerControllerEditedImage"];
    [self.imageButton setImage:image forState:UIControlStateNormal];
    [self dismissViewControllerAnimated:YES completion:nil];
    //使用异步的方式将图片保存到沙盒的代码块
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //获取应用的沙盒目录路径数组
    //    NSSearchPathForDirectoriesInDomains: 这是一个 Foundation 框架提供的函数,用于获取指定域中指定文件夹的路径。在这里,我们使用它来获取 "Documents" 目录的路径。
    //    NSDocumentDirectory: 这是一个枚举值,表示我们想要获取的文件夹是应用程序沙盒中的 "Documents" 目录。"Documents" 目录是应用程序可以存储用户数据的地方。
    //    NSUserDomainMask: 这是一个枚举值,指定了我们要在哪个域中搜索路径。NSUserDomainMask 表示搜索用户的主目录。
    //    YES: 这是一个布尔值,表示是否展开波浪线 ("~") 缩写。设置为 YES 表示展开波浪线,得到的路径将是完整的绝对路径。
    //    NSArray *docs: 这是一个包含路径的数组,其中第一个元素就是 "Documents" 目录的路径。
        NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        //docs[0]就是"Documents" 目录的路径,然后将照片保存为A48538182112B436F433E06CD04E131A.jpg
        NSString *imagePath = [docs[0]stringByAppendingPathComponent:@"A48538182112B436F433E06CD04E131A.jpg"];
        //将图片转换为 PNG 格式的二进制数据
        NSData *imageData = UIImagePNGRepresentation(image);
        //将图片的二进制数据写入文件,实现保存文件到沙盒的操作。atomically:YES表示写入操作要么完全成功,要么完全不成功,确保文件的完整性
        [imageData writeToFile:imagePath atomically:YES];
    });
}

以下是一些 UIImagePickerControllerInfoKey 中定义的常见键:
UIImagePickerControllerMediaType : 表示媒体的类型,是图片还是视频。
UIImagePickerControllerOriginalImage : 表示原始图片。
UIImagePickerControllerEditedImage : 表示用户编辑后的图片。
UIImagePickerControllerMediaURL: 表示媒体的 URL,通常用于视频。

运行结果:


调用相机

objectivec 复制代码
UIImagePickerController* imagePicker = [[UIImagePickerController alloc] init];
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]; //判断相机可不可用
        if (!isCamera) {
            NSLog(@"没有摄像头");
            return;
        }
        imagePicker.delegate = self;   //设置代理
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; //数据来源于相机
        imagePicker.allowsEditing = YES;
            NSLog(@"=======确认使用相机========");
        }];
  • 相机的类型:
objectivec 复制代码
typedef NS_ENUM(NSInteger, UIImagePickerControllerCameraDevice) {
    UIImagePickerControllerCameraDeviceRear, //后置摄像头
    UIImagePickerControllerCameraDeviceFront //前置摄像头
} 
相关推荐
大飞记Python7 小时前
刚从 Win 转 Mac?鼠标滚轮反向、触控板乱跑、第三方鼠标卡顿——这一篇就够了
macos·计算机外设·mac鼠标
国科安芯19 小时前
核电站仪控与监测系统中抗辐射 MCU 芯片应用研究
单片机·嵌入式硬件·macos·无人机·cocos2d·核电站
@大迁世界20 小时前
14个你现在必须关闭的 iOS 26 设置,不然手机很快被它榨干
macos·ios·智能手机·objective-c·cocoa
健忘的萝卜20 小时前
Clawdbot 爆红硅谷,也把 AI Agent 和 Mac mini 推上风口
人工智能·macos·agent·数字员工·clawbot
YJlio1 天前
10.2.8 以其他账户运行服务(Running services in alternate accounts):为什么“把服务切到某个用户账号下运行”,本质上是在改变服务的整个安全上下文?
python·安全·ios·机器人·django·iphone·7-zip
HashFlag1 天前
Mac新机基础配置
macos
承渊政道1 天前
【动态规划算法】(子序列问题解题框架与典型案例)
数据结构·c++·学习·算法·leetcode·macos·动态规划
pop_xiaoli1 天前
【iOS】KVC与KVO
笔记·macos·ios·objective-c·cocoa
SkyXZ~1 天前
Mac上使用VScode优雅开发STM32
vscode·stm32·macos
90后的晨仔1 天前
《swiftUI进阶 第10章:现代状态管理(iOS 17+)》
ios