iOS系统相册的有关操作

时间:2023-03-09 04:16:16
iOS系统相册的有关操作

  iOS中,我们选择相册中的资源和调用摄像头可以使用 :UIImagePickerController类来完成,不使用UI我们可以通过:ALAssetsLibrary类来使用相册资源。

一. ALAssetsLibrary简介

ALAssetsLibrary提供了访问了iOS设备下所有照片和视频的接口

1. 从ALAssetLibrary中可以读取所有的相册数据 用ALAssetsGroup对象列表;

2. 从每个ALAssetsGroup中可获取到其中包含的照片或视频列表,即ALAsset对象列表;

3. 每个ALAsset可能有多个representations表示,即ALAssetRepresentation对象,使用其defaultRepresentation方法可获得其默认representations,使用[asset valueForProperty:ALAssetPropertyRepresentations]可获取其所有representations的数组。

4. 从ALAsset对象可获取缩略图thumbnail或aspectRatioThumbnail;

5. 从ALAssetRepresentation对象可获取全尺寸图片(fullResolutionImage),全屏图片 (fullScreenImage)及图片的各种属性:orientation,dimensions,scale,url,metadata等。

其层次关系为ALAssetsLibrary ->ALAssetsGroup ->ALAsset ->ALAssetRepresentation.

二 . ALAssetsLibrary的使用

ALAssetsLibrary被封装在框架中。所以在使用时,我们需要引入AssetsLibrary.framework 在使用时需要引入头文件:

#import <AssetsLibrary/ALAssetsLibrary.h>

#import <AssetsLibrary/ALAssetsGroup.h>

#import <AssetsLibrary/ALAsset.h>

#import <AssetsLibrary/ALAssetRepresentation.h>

获得相册中的所有图片 

ALAssetsLibrary * library = [[ALAssetsLibrary alloc] init];

//遍历所有相册

[library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

//遍历每个相册

[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {

//可以通过valueForProperty获取到图片的信息,包括类型, Location , 时长,方向,日期,格式 , URL地址。

NSString * assetType = [result valueForProperty:ALAssetPropertyType];

if ([assetType isEqualToString:ALAssetTypePhoto]) {

//设置图片的属性

ALAssetRepresentation * assetRepresenttation = [result defaultRepresentation];

CGFloat imageScale = [assetRepresenttation scale];

UIImageOrientation imageOrientation = (UIImageOrientation)[assetRepresenttation orientation];

CGImageRef imageReference = [assetRepresenttation fullResolutionImage];

//对找到的图片进行操作

UIImage * image = [[UIImage alloc] initWithCGImage:imageReference scale:imageScale orientation:imageOrientation];

if (image != nil) {

//获取到所有图片 把所有图片添加到数组中

}else{

NSLog(@"Failed to create the image");

}

}

}];

} failureBlock:^(NSError *error) {

}];

三 . UIImagePickerController详解

iOS获取图片有三种方法

1.直接调用摄像头拍照

2.从相册中选择

3.从图库中选择

UIImagePickerController 是系统提供的来获取图片和视频的接口,用UIImagePickerController类来获取图片视频,大题分为以下几个步骤:

1、初始化UIImagePickerController类

2、设置UIImagePickerController实例的数据来源类型(详情见下);

3、设置代理;

4、如果需要做图片修改的话设置allowsEditing= YES;

数据来源类型一共有三种:

typedef NS_ENUM(NSInteger, UIImagePickerControllerSourceType) {

UIImagePickerControllerSourceTypePhotoLibrary,                //来自图库

UIImagePickerControllerSourceTypeCamera,                       //来自手机

UIImagePickerControllerSourceTypeSavedPhotosAlbum       //来自相册

} __TVOS_PROHIBITED;

在用这些来源的时候最好检测以下设备是否支持:

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){

     NSLog(@"支持相机");

}

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {

NSLog(@"支持图库");

}

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {

NSLog(@"支持相片库");

}

调用摄像头来获取资源

    picker = [[UIImagePickerController alloc]init];
    picker.view.backgroundColor = [UIColor orangeColor];
    UIImagePickerControllerSourceType sourcheType = UIImagePickerControllerSourceTypeCamera;
    picker.sourceType = sourcheType;
    picker.delegate = self;
    picker.allowsEditing = YES;
上面只是实例化了UIImagePickerController及其属性 在需要获取图片的时候需要弹出窗口调用
  [self presentViewController:picker animated:YES completion:nil];

当用户选取完成后调用:

- (void)imagePickerController:(UIImagePickerController *)picker
       didFinishPickingMediaWithInfo:(NSDictionary *)info;
当用户取消选取时调用:

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

选取的信息在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

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;
一个示例 :

#import "ViewController.h"

@interface ViewController ()<UITextViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

{

//输入框

UITextView * _textEditor;

//下拉菜单

UIActionSheet * myActionSheet;

//图片2进制路径

NSString * filePath;

}

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

self.view.backgroundColor = [UIColor blackColor];

self.automaticallyAdjustsScrollViewInsets = NO;

self.navigationItem.title = @"逆的态度的输入框";

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStyleDone target:self action:@selector(sendInfo)];

//输入框显示区域

_textEditor = [[UITextView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width , 300)];

_textEditor.backgroundColor = [UIColor brownColor];

//设置它的代理

_textEditor.delegate = self;

_textEditor.keyboardType = UIKeyboardTypeDefault;

_textEditor.font = [UIFont systemFontOfSize:20];

//默认软键盘是不会打开的

[_textEditor becomeFirstResponder];

[self.view addSubview:_textEditor];

//下方的图片按钮 点击后呼出菜单 打开摄像机 查找本地相册

UIImage *image = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"car-add" ofType:@"png"]];

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

button.frame = CGRectMake(0, _textEditor.frame.size.height + 64, 35, 40);

[button setImage:image forState:UIControlStateNormal];

[button addTarget:self action:@selector(openMenu) forControlEvents:UIControlEventTouchUpInside];

//把它也加在视图当中

[self.view addSubview:button];

}

#pragma mark - 打开菜单 -

-(void)openMenu

{

//在这里呼出下方菜单按钮项

myActionSheet = [[UIActionSheet alloc]

initWithTitle:nil

delegate:self

cancelButtonTitle:@"取消"

destructiveButtonTitle:nil

otherButtonTitles: @"打开照相机", @"从手机相册获取",nil];

[myActionSheet showInView:self.view];

[_textEditor resignFirstResponder];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

{

//呼出的菜单按钮点击后的响应

if (buttonIndex == myActionSheet.cancelButtonIndex)

{

NSLog(@"取消");

}

switch (buttonIndex) {

case 0:

//打开照相机拍照

[self takePhoto];

break;

case 1:

//打开本地相册

[self LocalPhoto];

break;

default:

break;

}

}

#pragma mark - 开始拍照 -

- (void)takePhoto

{

UIImagePickerControllerSourceType sourceType  = UIImagePickerControllerSourceTypeCamera;

if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

UIImagePickerController *picker = [[UIImagePickerController alloc] init];

picker.delegate = self;

picker.allowsEditing = YES;

picker.sourceType = sourceType;

[self presentViewController:picker animated:YES completion:^{

}];

}else{

NSLog(@"模拟器无法打开照相机,请在真机中使用");

}

}

#pragma mark  - 打开本地相册 -

- (void)LocalPhoto

{

UIImagePickerController * picker = [[UIImagePickerController alloc] init];

picker.sourceType  = UIImagePickerControllerSourceTypePhotoLibrary;

picker.delegate = self;

//设置选择后的图片可被编辑

picker.allowsEditing = YES;

[self presentViewController:picker animated:YES completion:^{

}];

}

#pragma mark - 发送消息 -

- (void)sendInfo

{

NSLog(@"图片的路径是:%@",filePath);

NSLog(@"你输入框中的内容是:%@",_textEditor.text);

}

#pragma mark - ImagePickerControllerDelegate -

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

{

NSString * type = [info objectForKey:UIImagePickerControllerMediaType];

if ([type isEqualToString:@"public.image"]) {

//先把图片转成NSData

UIImage * image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

NSData  * data;

if (UIImagePNGRepresentation(image) == nil) {

data = UIImageJPEGRepresentation(image, 1.0);

}else{

data = UIImagePNGRepresentation(image);

}

//图片保存的路径

NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

//文件管理器

NSFileManager * fileManager = [NSFileManager defaultManager];

//把刚刚的图片转换的data对象拷贝至沙盒中 并保存为image.png

[fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];

[fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];

//得到选择后沙盒中图片的完整路径

filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,@"/image.png"];

//关闭相册界面

[picker dismissViewControllerAnimated:YES completion:^{

}];

//创建一个选择后图片的小图标放在下方

UIImageView * smallimage = [[UIImageView alloc] initWithFrame:CGRectMake(35, _textEditor.frame.size.height + 68, 35, 35)];

smallimage.image = image;

[self.view addSubview:smallimage];

}

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

NSLog(@"你取消了选择图片");

[picker dismissViewControllerAnimated:YES completion:^{

}];

}

@end