一行代码搞定图片选择

//
// gzhPhotoManager.h
// 图片选择
//
// Created by 郭志贺 on 2020/5/26.
// Copyright © 2020 郭志贺. All rights reserved.
// #import <Foundation/Foundation.h>
#import "ViewController.h" NS_ASSUME_NONNULL_BEGIN
@protocol gzhPhotoManagerDelegate;
@interface gzhPhotoManager : NSObject +(instancetype)instance; /// 选择图片
/// @param controller 当前控制器
/// @param target 代理
/// @param pSize 选择照片尺寸 尺寸传(0,0)不进行裁剪
- (void)selectPhotoWithController:(UIViewController *)controller delegate:(id)target size:(CGSize)pSize; @end @protocol gzhPhotoManagerDelegate <NSObject> - (void)selectedPhotoImage:(UIImage *)image; @end
NS_ASSUME_NONNULL_END
 //
// gzhPhotoManager.m
// 图片选择
//
// Created by 郭志贺 on 2020/5/26.
// Copyright © 2020 郭志贺. All rights reserved.
// #import "gzhPhotoManager.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <Photos/Photos.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <MetalPerformanceShaders/MetalPerformanceShaders.h> @interface gzhPhotoManager () <UINavigationControllerDelegate,UIImagePickerControllerDelegate> @property (nonatomic, weak) id<gzhPhotoManagerDelegate> delegate;
@property (nonatomic, assign) CGSize photoSize;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, weak) UIViewController *controller;
@property (nonatomic, strong) UIImagePickerController *imagePickerController; @end @implementation gzhPhotoManager + (instancetype)instance {
static gzhPhotoManager * shareInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareInstance = [[gzhPhotoManager alloc]init];
});
return shareInstance;
}
-(void)selectPhotoWithController:(UIViewController *)controller delegate:(id)target size:(CGSize)pSize{ _controller = controller;
_delegate = target;
_photoSize = pSize; UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
[alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [self cameraCheck:action];
}]];
[alertVC addAction:[UIAlertAction actionWithTitle:@"从手机相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [self phAuthorizationCheck:action];
}]];
[_controller presentViewController:alertVC animated:YES completion:nil];
}
-(void)cameraCheck:(UIAlertAction *)action{
/*
AVAuthorizationStatusNotDetermined = 0,// 系统还未知是否访问,第一次开启相机时 AVAuthorizationStatusRestricted, // 受限制的 AVAuthorizationStatusDenied, //不允许 AVAuthorizationStatusAuthorized // 允许状态
*/ ALAuthorizationStatus author =[ALAssetsLibrary authorizationStatus];
if (author == AVAuthorizationStatusRestricted || author ==AVAuthorizationStatusDenied) {
[self alertViewWithTitle:@"提示" message:@"如需拍照,请检查拍照功能是否开启,可在:设置->隐私->照相.设置"];
}else if (author == AVAuthorizationStatusAuthorized){
[self selectCamera:action];
}else if (author == AVAuthorizationStatusNotDetermined){
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) { if (granted) { //允许访问
[self selectCamera:action];
}else{ //不允许访问
[self alertViewWithTitle:@"提示" message:@"如需拍照,请检查拍照功能是否开启,可在:设置->隐私->照相.设置"];
} }];
} } //判断是否有权限访问相簿
- (void)phAuthorizationCheck:(UIAlertAction *)action{
/*
PHAuthorizationStatusNotDetermined, 用户还没有做出选择
PHAuthorizationStatusDenied, 用户拒绝当前应用访问相册(用户当初点击了"不允许")
PHAuthorizationStatusAuthorized 用户允许当前应用访问相册(用户当初点击了"好")
PHAuthorizationStatusRestricted, 因为家长控制, 导致应用无法方法相册(跟用户的选择没有关系)
*/ // 判断授权状态
PHAuthorizationStatus statu = [PHPhotoLibrary authorizationStatus];
if (statu == PHAuthorizationStatusRestricted) {
NSLog(@"无法访问相簿--PHAuthorizationStatusRestricted");
[self alertViewWithTitle:@"提示" message:@"如需拍照,请检查拍照功能是否开启,可在:设置->隐私->照片.设置"];
} else if (statu == PHAuthorizationStatusDenied) {
NSLog(@"无法访问相簿--PHAuthorizationStatusDenied");
[self alertViewWithTitle:@"提示" message:@"如需拍照,请检查拍照功能是否开启,可在:设置->隐私->照片.设置"];
} else if (statu == PHAuthorizationStatusAuthorized) {
NSLog(@"可以访问相簿--PHAuthorizationStatusAuthorized");
[self selectPhotoLibrary:action];
} else if (statu == PHAuthorizationStatusNotDetermined) {
// 弹框请求用户授权
NSLog(@"第一次访问--PHAuthorizationStatusNotDetermined");
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { if (status == PHAuthorizationStatusAuthorized) {
[self selectPhotoLibrary:action];
}else{
[self alertViewWithTitle:@"提示" message:@"如需拍照,请检查拍照功能是否开启,可在:设置->隐私->照片.设置"];
} }]; } }
// 拍照
- (void)selectCamera:(UIAlertAction *)action {
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
dispatch_async(dispatch_get_main_queue(), ^{
[self alertViewWithTitle:@"警告" message:@"对不起,您的设备不存在相机"];
}); return;
} if (!_imagePickerController) {
_imagePickerController = [UIImagePickerController new];
_imagePickerController.delegate = self;
}
if (_photoSize.width!=&&_photoSize.height!=) {
_imagePickerController.allowsEditing = YES;
}else{
_imagePickerController.allowsEditing = NO;
} _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
_imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
[_controller presentViewController:_imagePickerController animated:YES completion:nil];
} // 从相册中选择
- (void)selectPhotoLibrary:(UIAlertAction *)action {
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
dispatch_async(dispatch_get_main_queue(), ^{
[self alertViewWithTitle:@"警告" message:@"对不起,您的设备不存在相册"];
}); }
if (!_imagePickerController) {
_imagePickerController = [UIImagePickerController new];
_imagePickerController.delegate = self;
}
if (_photoSize.width!=&&_photoSize.height!=) {
_imagePickerController.allowsEditing = YES;
}else{
_imagePickerController.allowsEditing = NO;
}
_imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage,(NSString *)kUTTypeMovie];
_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[_controller presentViewController:_imagePickerController animated:YES completion:nil]; }
#pragma mark -
#pragma mark - UIImagePickerViewController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString * mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
if (_photoSize.height!=&&_photoSize.width!=) {
UIImage *image = [self fixOrientation:[info objectForKey:UIImagePickerControllerEditedImage]];
self.image = [self scaleImage:image Tosize:self.photoSize];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}else{
UIImage *image = [self fixOrientation:[info objectForKey:UIImagePickerControllerOriginalImage]];
self.image = [self scaleImage:image Tosize:self.photoSize];
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
}
[picker dismissViewControllerAnimated:YES completion:^{
if (self.delegate && [self.delegate respondsToSelector:@selector(selectedPhotoImage:)]) {
if (self.image) {
[self.delegate selectedPhotoImage:self.image];
} else {
[self alertViewWithTitle:@"你还没选择图片呢" message:nil];
}
}
}];
} } -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:nil];
}
// 裁剪图片
- (UIImage *)scaleImage:(UIImage *)img Tosize:(CGSize)size { CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGSize imgSize = CGSizeMake(, );
if (size.width != && size.height != ) {
imgSize = CGSizeMake(size.width, img.size.height*(size.width/img.size.width));
} else {
imgSize = CGSizeMake(screenWidth*, img.size.height*(screenWidth/img.size.width)*);
}
// 创建一个bitmap的context
// 并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(imgSize);
// 绘制改变大小的图片
[img drawInRect:CGRectMake(, , imgSize.width, imgSize.height)];
// 从当前context中创建一个改变大小后的图片
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
//返回新的改变大小后的图片
return scaledImage;
} //修正image方向
- (UIImage *)fixOrientation:(UIImage *)aImage { if (aImage.imageOrientation == UIImageOrientationUp)
return aImage; CGAffineTransform transform = CGAffineTransformIdentity; switch (aImage.imageOrientation) {
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
transform = CGAffineTransformRotate(transform, M_PI);
break; case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, );
transform = CGAffineTransformRotate(transform, M_PI_2);
break; case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, , aImage.size.height);
transform = CGAffineTransformRotate(transform, -M_PI_2);
break;
default:
break;
} switch (aImage.imageOrientation) {
case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.width, );
transform = CGAffineTransformScale(transform, -, );
break; case UIImageOrientationLeftMirrored:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, aImage.size.height, );
transform = CGAffineTransformScale(transform, -, );
break;
default:
break;
} CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
CGImageGetBitsPerComponent(aImage.CGImage), ,
CGImageGetColorSpace(aImage.CGImage),
CGImageGetBitmapInfo(aImage.CGImage));
CGContextConcatCTM(ctx, transform);
switch (aImage.imageOrientation) {
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
// Grr...
CGContextDrawImage(ctx, CGRectMake(,,aImage.size.height,aImage.size.width), aImage.CGImage);
break; default:
CGContextDrawImage(ctx, CGRectMake(,,aImage.size.width,aImage.size.height), aImage.CGImage);
break;
} // And now we just create a new UIImage from the drawing context
CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
UIImage *img = [UIImage imageWithCGImage:cgimg];
CGContextRelease(ctx);
CGImageRelease(cgimg);
return img;
} // 提醒
- (void)alertViewWithTitle:(NSString *)title message:(NSString *)msg {
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
[alertVC addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
[_controller presentViewController:alertVC animated:YES completion:nil];
} @end

在需要使用的地方遵循<gzhPhotoManagerDelegate>协议

 //
// ViewController.m
// 图片选择
//
// Created by 郭志贺 on 2020/5/26.
// Copyright © 2020 郭志贺. All rights reserved.
// #import "ViewController.h"
#import "gzhPhotoManager.h" /** 屏幕高度 */
#define ScreenH [UIScreen mainScreen].bounds.size.height
/** 屏幕宽度 */
#define ScreenW [UIScreen mainScreen].bounds.size.width @interface ViewController ()<gzhPhotoManagerDelegate>
@property(nonatomic,strong)UIImageView * selectImageView;
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view. _selectImageView = [[UIImageView alloc]init];
_selectImageView.frame = CGRectMake(, , ScreenW, ScreenH);
_selectImageView.contentMode = UIViewContentModeScaleAspectFit;
_selectImageView.clipsToBounds = YES;
_selectImageView.backgroundColor = [UIColor purpleColor];
[self.view addSubview:_selectImageView]; _selectImageView.userInteractionEnabled = YES;
UITapGestureRecognizer * selectPhotoTapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectPhoto:)];
[_selectImageView addGestureRecognizer:selectPhotoTapGes]; }
-(void)selectPhoto:(UITapGestureRecognizer *)taps{
//调用
[[gzhPhotoManager instance]selectPhotoWithController:self delegate:self size:CGSizeMake(ScreenW, ScreenW)]; }
-(void)selectedPhotoImage:(UIImage *)image{ _selectImageView.image = image; }
@end

可直接复制使用,新手见解,如有遗漏或不足敬请告知。

iOS开发图片选择-LMLPHP

05-11 18:16