iOS 系统- 相册与 拍照

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface SystemImagePickerManager : NSObject
/// 创建这样一个管理类对象
- (instancetype)initWithViewController:(UIViewController *)VC;
///选择图片的回调block
@property (nonatomic,copy) void(^didSelectImageBlock) (UIImage *image);
/// 相册选择器对象
@property (nonatomic,strong) UIImagePickerController *imagePicker;
///最大视频时长
@property (nonatomic,assign) NSTimeInterval videoMaximumDuration;
//是否支持视屏选择
@property (nonatomic,assign) BOOL isVideo;

@property (nonatomic,assign) BOOL allowsEditing;

///快速创建一个图片选择弹出窗
- (void)quickAlertSheetPickerImage ;

///打开相机
- (void)openCamera;

///打开相册
- (void)openPhotoLibrary ;

@end

NS_ASSUME_NONNULL_END

#import "SystemImagePickerManager.h"

@interface SystemImagePickerManager ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
///来源控制器
@property (nonatomic,strong) UIViewController *orginViewController;
/// 取出的图片
@property (nonatomic,strong) UIImage *tempImage;

@end

@implementation SystemImagePickerManager

- (UIImagePickerController *)imagePicker{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.delegate = self;
            /// 转场动画方式
//      _imagePicker.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        _imagePicker.allowsEditing = YES; //允许编辑
        _imagePicker.videoMaximumDuration = 15 ; //视频时长默认15s
        _imagePicker.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }
    return _imagePicker;
}

- (void)setAllowsEditing:(BOOL)allowsEditing {
    _allowsEditing = allowsEditing;
    self.imagePicker.allowsEditing = allowsEditing; //允许编辑
}

- (void)setIsVideo:(BOOL)isVideo{
    _isVideo = isVideo;
    if (isVideo == YES) {
            /// 媒体类型
    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage,(NSString *)kUTTypeMovie];
    }else{
            /// 媒体类型
    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    }
}

- (instancetype)initWithViewController:(UIViewController *)VC{
    self = [super init];
    if (self) {
       self.orginViewController = VC;
    }
    return self;
}

#pragma mark- 快速创建一个图片选择弹出窗
- (void)quickAlertSheetPickerImage{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    [alertVc addAction:takePhotoAction];
    UIAlertAction *imagePickerAction = [UIAlertAction actionWithTitle:@"去相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openPhotoLibrary];
    }];
    [alertVc addAction:imagePickerAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVc addAction:cancelAction];
    [self.orginViewController presentViewController:alertVc animated:YES completion:nil];
}

- (void)openCamera {
    AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"未获得授权使用相机,请在iOS\"设置中\"-\"隐私\"-\"相机\"中打开" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:conform];
        [self.orginViewController presentViewController:alert animated:YES completion:nil];
        return;

    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        // fix issue 466, 防止用户首次拍照拒绝授权时相机页黑屏
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self openCamera];
                });
            }
        }];
    }
    else {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self.orginViewController presentViewController:self.imagePicker animated:YES completion:nil];
    }
}

- (void)openPhotoLibrary {
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
           dispatch_async(dispatch_get_main_queue(), ^{
               switch (status) {
                   case PHAuthorizationStatusAuthorized: //已获取权限
                   {
                       [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
                       self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                       self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
                       [self.orginViewController presentViewController:self.imagePicker animated:YES completion:nil];
                   }
                       break;
                   case PHAuthorizationStatusDenied: //用户已经明确否认了这一照片数据的应用程序访问
                   {
                       UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"未获得授权使用相机,请在iOS\"设置中\"-\"隐私\"-\"相册\"中打开" preferredStyle:UIAlertControllerStyleAlert];
                       UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                       [alert addAction:conform];
                       [self.orginViewController presentViewController:alert animated:YES completion:nil];
                       return ;
                   }
                       break;
                   case PHAuthorizationStatusRestricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限
                   {
                       UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"未获得授权使用相机,请在iOS\"设置中\"-\"隐私\"-\"相册\"中打开" preferredStyle:UIAlertControllerStyleAlert];
                       UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                       [alert addAction:conform];
                       [self.orginViewController presentViewController:alert animated:YES completion:nil];
                       return ;
                   }
                       break;
                       
                   default:
                   {
                       UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"访问相册失败" preferredStyle:UIAlertControllerStyleAlert];
                       UIAlertAction *conform = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                       [alert addAction:conform];
                       [self.orginViewController presentViewController:alert animated:YES completion:nil];
                       return;
                   }
                       break;
               }
           });
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [[UIBarButtonItem appearance] setTintColor:nil];
    
    if (self.allowsEditing) {
        UIImage *orginImage = info[UIImagePickerControllerEditedImage];
        self.tempImage = [self fixOrientation:orginImage];
    } else {
        UIImage *orginImage = info[UIImagePickerControllerOriginalImage];
        self.tempImage = [self fixOrientation:orginImage];
    }
    /// 选择的图片
    if(self.didSelectImageBlock){
        self.didSelectImageBlock(self.tempImage);
    }
    ///拍到的照片顺带保存到相册
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        [self saveImageToSystemPhotosAlbum];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [[UIBarButtonItem appearance] setTintColor:nil];
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark- 拍的照片保存到系统相册
- (void)saveImageToSystemPhotosAlbum{
    UIImageWriteToSavedPhotosAlbum(self.tempImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

/// 系统指定的回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    NSLog(@"%@",msg);
}

///矫正图片方向
- (UIImage*)fixOrientation:(UIImage*)aImage
{
        // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;

        // We need to calculate the proper transformation to make the image upright.
        // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    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, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, 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, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }

        // Now we draw the underlying CGImage into a new context, applying the transform
        // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0, 0, aImage.size.height, aImage.size.width), aImage.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0, 0, 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;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 227,572评论 6 531
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,071评论 3 414
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 175,409评论 0 373
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 62,569评论 1 307
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,360评论 6 404
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,895评论 1 321
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,979评论 3 440
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,123评论 0 286
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,643评论 1 333
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,559评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,742评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,250评论 5 356
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,981评论 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,363评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,622评论 1 280
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,354评论 3 390
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,707评论 2 370

推荐阅读更多精彩内容