iOS 相机调用相册打开及图片头像的上传到服务器详解

首先要遵守代理: <span style="color: rgb(0, 175, 202); font-family: Menlo; font-size: 14px; font-variant-ligatures: no-common-ligatures;">UIImagePickerControllerDelegate</span><span style="font-family: Menlo; font-size: 14px; font-variant-ligatures: no-common-ligatures; color: rgb(255, 255, 255);">, </span><span style="color: rgb(0, 175, 202); font-family: Menlo; font-size: 14px; font-variant-ligatures: no-common-ligatures;">UINavigationControllerDelegate</span>
    // 创建 提示
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"设置头像" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    // 添加按钮
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
         // 初始化
         _imagePickerController = [[UIImagePickerController alloc] init];
         // 支持的 类型  为 相机
         _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
         // 设置  相机 支持的功能 (拍照,视频)(注意: 转化类型~)
         _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
         _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
         _imagePickerController.delegate = self;
        _imagePickerController.allowsEditing = YES;
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }];
    UIAlertAction *loginAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 相册
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    UIAlertAction *quxiaoAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];

    [alertController addAction:cancelAction];
    [alertController addAction:quxiaoAction];
    [alertController addAction:loginAction];
    [self presentViewController:alertController animated:YES completion:nil];

最主要要实现的代理方法

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
        // 获取当前类型
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    //判断
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
    //这是拍照的

    UIImage *images = [info objectForKey:UIImagePickerControllerOriginalImage]; 
        UIImage *image = [self imageWithImageSimple:images scaledToSize:CGSizeMake(250, 250)];// 压缩图片
        _imageP = image;
    // 保存图片到本地, 上传图片到服务器需要使用
    NSString *nowTime = [NSString stringWithFormat:@"%@.png",[OSRequestManager getTimesTamp]];
    [self saveImage:image withName:nowTime];
    // 取出图片
    NSString *fullPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:nowTime];
        NSLog(@"%@",fullPath);
    UIImage *saveImage = [[UIImage alloc] initWithContentsOfFile:fullPath];


    //  保存到相册中, 需要使用函数
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

    [_imageV setImage:saveImage];
    [OSFileManager shareHandle].isClickPhoto = YES;
    _isChangPhoto = NO;
    
 }
// 压缩图片

- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;

}
// 保存图片

// 保存图片

- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1);
    // 获取沙盒目录
    
   NSString *fullPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:imageName];
   [imageData writeToFile:fullPath atomically:NO];
}
// 上传方法

      AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];        
        NSMutableDictionary *par = [NSMutableDictionary dictionary];
        par[@"user_id"] = models.user_id;
        par[@"name"] = name;
        par[@"mobile"] = _phoneNumberField.text;
        par[@"public_key"] = @"youin_app";
        par[@"timestamp"] = timeStr;
        par[@"sign"] = sign;
        par[@"file"] = UIImagePNGRepresentation(_imageP);
        AFHTTPRequestOperation *httpOperation = [manager POST:url parameters:par constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            
            _imageData = UIImagePNGRepresentation(_imageP);
            [formData appendPartWithFileData:_imageData name:@"file" fileName:@"icon.png" mimeType:@"image/png"];// 主要
        } success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // 到这一步一般上传就成功了 
            NSLog(@"operation.responseString == %@",operation.responseString);

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];






你可能感兴趣的:(iOS 相机调用相册打开及图片头像的上传到服务器详解)