博客> iOS-相册照片和拍照功能
iOS-相册照片和拍照功能
2017-10-20 03:38 评论:0 阅读:366 OS_JJ
ios 相册照片和拍照功能

一.使用 UIPickerViewController 自定义相机和相册功能

备用:

   1.  在info.plist里面添加Localized resources can be mixed设置为YES(表示是否允许应用程序获取框架库内语言) 

    2.提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - 秀贝] 打开访问开关" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //确定按钮点击事件处理
        }]];
    [self presentViewController:alert animated:YES completion:nil];

第一步.添加点击相片按钮的点击事件

        - (void)addImaBtnClick{
            _myActionSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

            [_myActionSheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                [self takePhoto];

            }]];
            [_myActionSheet addAction:[UIAlertAction actionWithTitle:@"从手机相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                [self LocalPhoto];

            }]];

            [_myActionSheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
            [self presentViewController:_myActionSheet animated:YES completion:nil];
        }

第二步.调用相机方法

    - (void)takePhoto{
      if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate = self;
            picker.allowsEditing = YES;/** 设置拍照后的图片可被编辑 */
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;

            //录制视频时长,默认10s
            picker.videoMaximumDuration = 15;
            //相机类型(拍照、录像...)字符串需要做相应的类型转换
            picker.mediaTypes = @[(NSString *)kUTTypeMovie,(NSString *)kUTTypeImage];
            picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
            //设置摄像头模式(拍照,录制视频)为录像模式
            picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModeVideo;

            [self presentViewController:picker animated:YES completion:^{
                [UIApplication sharedApplication].statusBarHidden = YES;;
            }];
        }else{
            NSLog(@"模拟机无法打开照相机,请在真机使用");
        }
    }

第三步.打开本地相册

        -(void)LocalPhoto
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.delegate = self;
            //设置选择后的图片可被编辑
            picker.allowsEditing = YES;
            [self presentViewController:picker animated:YES completion:nil];
        }

第四步.当选择一张照片后进入这里

    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString> *)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);
            }

            //图片保存的路径
            //这里将图片放在沙盒的documents文件夹中
            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:nil];

            [self.imageArr addObject:image];
            NSData * imgData = [JKWImagePost compactImage:image];
            [self.dataArray addObject:imgData];
            //创建一个选择后图片的小图标放在下方,类似微薄选择图后的效果
            if (_imageArr.count < 10 xss=removed xss=removed>= 3)
                    {
                        x = 20 + 74 * (_imageArr.count % 4);
                        y = 160 + (HEIGHT - 70) / 3 + 74 * ( _imageArr.count / 4);
                }

                UIImageView *smallimage = [[UIImageView alloc]initWithFrame:CGRectMake(x, y, 64, 64)];
                [self.imageViewArr addObject:smallimage];

                UIImageView *sun = _imageViewArr[_imageArr.count-1];
                UIImage *cao = _imageArr[_imageArr.count-1];
                sun.image = cao;
                //        smallimage.image = image;
                //加在视图中
                [self.view addSubview:sun];

                UIButton *picBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                picBtn.frame = CGRectMake(x, y, 64, 64);
                picBtn.tag = 2013 + _imageArr.count - 1;
                [picBtn addTarget:self action:@selector(picBtnClick:) forControlEvents:UIControlEventTouchUpInside];
                [self.view addSubview:picBtn];
                [self.picBtnArray addObject:picBtn];

    //            [self performSelector:@selector(setImageArr:) withObject:nil afterDelay:1];
            }else{

                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"一次最多只能上传九张!" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:nil];
            }

        }

    }

    -(void)picBtnClick:(UIButton *)sender
    {

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"您确定要删除该照片吗?" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImageView *picImage = [self.imageViewArr objectAtIndex:self.imageViewArr.count - 1];
            [picImage removeFromSuperview];
            [self.imageViewArr removeObjectAtIndex:self.imageViewArr.count - 1];
            [_imageArr removeObjectAtIndex:sender.tag - 2013];
            [self.dataArray removeObjectAtIndex:sender.tag - 2013];
            UIButton *picBtn = [self.picBtnArray objectAtIndex:self.picBtnArray.count - 1];
            [picBtn removeFromSuperview];
            [self.picBtnArray removeObjectAtIndex:self.picBtnArray.count - 1];
            [self.picArray removeAllObjects];
            for (int i = 0; i < self xss=removed xss=removed> *)info{
        NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
        //判断资源类型
        if ([mediaType isEqualToString:(NSString *)kUTTypeImage]){
            //如果是图片
            UIImage *image = info[UIImagePickerControllerEditedImage];
            NSLog(@"图片是%@",image);
    //        self.imageView.image = info[UIImagePickerControllerEditedImage];
    //        //压缩图片
    //        NSData *fileData = UIImageJPEGRepresentation(self.imageView.image, 1.0);
    //        //保存图片至相册
    //        UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    //        //上传图片
    //        [self uploadImageWithData:fileData];

        }else{
            //如果是视频
            NSURL *url = info[UIImagePickerControllerMediaURL];
            NSLog(@"视频链接是%@",url);
    //        //播放视频
    //        _moviePlayer.contentURL = url;
    //        [_moviePlayer play];
    //        //保存视频至相册(异步线程)
    //        NSString *urlStr = [url path];
    //        
    //        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr)) {
    //                
    //                UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
    //            }
    //        });
    //        NSData *videoData = [NSData dataWithContentsOfURL:url];
    //        //视频上传
    //        [self uploadVideoWithData:videoData];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }

    ///** 取消按钮回调 */
    //- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    //
    //}

    /* 图片保存完毕的回调 */
    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
        if (error) {
            NSLog(@"保存照片过程中发生错误,错误信息:%@",error.localizedDescription);
        }else{
            NSLog(@"照片保存成功.");
        }
    }

    /* 视频保存完毕的回调 */
    - (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
        if (error) {
            NSLog(@"保存视频过程中发生错误,错误信息:%@",error.localizedDescription);
        }else{
            NSLog(@"视频保存成功.");
        }
    }
收藏
0
sina weixin mail 回到顶部