ios ~ (相机、相册)图片发送、上传

作者: 阳光下的叶子呵 | 来源:发表于2021-06-24 11:01 被阅读0次

    遵守代理<UIImagePickerControllerDelegate>

    1、弹窗

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *CameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [weakself persentImagePicker:1];
                    
                }];
                UIAlertAction *AlbumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    [weakself persentImagePicker:2];
                    
                }];
                
                [alertController addAction:CameraAction];
                [alertController addAction:AlbumAction];
                [alertController addAction:cancelAction];
                [weakself presentViewController:alertController animated:YES completion:nil];
    

    2、 获取图片、照片

    //调用本地相册
    - (void)persentImagePicker:(int)type{
        if (!_imagePickerG) {
            ///初始化相机
            _imagePickerG = [[UIImagePickerController alloc]init];
            ///代理
            _imagePickerG.delegate = self;
        }
        if (type == 1) {//相机
            _imagePickerG.sourceType = UIImagePickerControllerSourceTypeCamera;
            _imagePickerG.allowsEditing = YES;
            [self.navigationController presentViewController:_imagePickerG animated:YES completion:nil];
        }else if (type == 2)//相册
        {
            _imagePickerG.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            _imagePickerG.allowsEditing = YES;
            [self.navigationController presentViewController:_imagePickerG animated:YES completion:nil];
        }
        
    }
    
    ///取消选择图片(拍照)
    - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
    ///选择图片完成(从相册或者拍照完成)
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
        //UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];///原图
        //获取修剪后的图片
        UIImage *imageUp = [info objectForKey:UIImagePickerControllerEditedImage];
        [self UpPic:imageUp];
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    /**
    ///选择图片完成(从相册或者拍照完成)
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];///原图
        //获取修剪后的图片
        //UIImage *imageUp = [info objectForKey:UIImagePickerControllerEditedImage];
        
        CGSize newSize = CGSizeMake(image.size.width*0.5, image.size.height*0.5);
        UIImage *tempimage = [self reSizeImage:image toSize:newSize];
        NSData *data = UIImageJPEGRepresentation(tempimage, 1);
        if (data.length/2014>=1000) {
            newSize = CGSizeMake(tempimage.size.width*0.7, tempimage.size.height*0.7);
            tempimage = [self reSizeImage:image toSize:newSize];
            data = UIImageJPEGRepresentation(tempimage, 1);
        }
    
        [self SendBaiDuPress:tempimage];
        self.wordImageView.image = tempimage;
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
    
    // 调整图片大小(这里是缩小图片)
    - (UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize
    {
        UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
        [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];
        UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return reSizeImage;
    }
    */
    
    ///保存图片到本地相册
    -(void)imageTopicSave:(UIImage *)image{
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image: didFinishSavingWithError: contextInfo:), nil);
    }
    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
        if (error == nil) {
            
        }
        else{
            ///图片未能保存到本地
        }
    }
    

    3、上传图片

    -(void)UpPic:(UIImage *)img
    {
        NSString *user_uuid = [[NSUserDefaults standardUserDefaults] objectForKey:@"user_uuid"];
        if(user_uuid == nil)
        {
            LoginViewCTRL *loginViewCTRL = [[LoginViewCTRL alloc] init];
            loginViewCTRL.loginVieCTRLBlock = ^{
                
            };
            [self.navigationController pushViewController:loginViewCTRL animated:YES];
            
        }else
        {
            NSString *postUrl=[NSString stringWithFormat:@"%@%@%@",ServerOtherUrl,ProjectName,@"/user/updatePicture.do"];
            
            NSDictionary *parameters=@{@"user_uuid":user_uuid
                                       };
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            NSData *imageData = UIImageJPEGRepresentation(img, 0.6);//image为要上传的图片(UIImage)
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [manager POST:postUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                //
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyyMMddHHmmss";
                NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
                //二进制文件,接口key值,文件路径,图片格式
                if (self.changePicType == 1)
                {
                    [formData appendPartWithFileData:imageData name:@"head_img" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
                }else if (self.changePicType == 2)
                {
                    [formData appendPartWithFileData:imageData name:@"cover_img" fileName:fileName mimeType:@"image/jpg/png/jpeg"];
                }
                
            } progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                NSLog(@"%@",task.currentRequest.URL);
                [self GainUserInfo];
    
     
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                //
                [MBProgressHUD hideHUDForView:self.view animated:YES];
            }];
        }
        
    }
    

    注意:使用AFNetworking的方法:上传图片

    //压缩图片
        NSData *imageData = UIImageJPEGRepresentation(image,0);
        //沙盒,准备保存的图片地址和图片名称
        NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
        formatter.dateFormat=@"yyyyMMddHHmmss";
        NSString *str=[formatter stringFromDate:[NSDate date]];
        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpeg",str]];
        //将图片写入文件中
        [imageData writeToFile:fullPath atomically:NO];
        //通过路径获取到保存的图片,可以在主界面上的image进行预览
        UIImage *saveImage = [[UIImage alloc]initWithContentsOfFile:fullPath];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer.timeoutInterval = 20;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
        gron_User;
        gron_self;
        [manager.requestSerializer setValue:gron_Token forHTTPHeaderField:gron_AFNKEY];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:@"1" forKey:@"flagFace"];
        [dict setObject:@"1" forKey:@"zipFlag"];
        [dict setObject:fullPath forKey:@"file"];
        
        NSString *url = @"https://xxx.com";
        
        MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        gron_hub;
        
        [manager POST:url parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
          /* 该方法参数
             appendPartWithFileData:要上传的照片二进制流
             name:对应后台要上传接口的参数名
             fileName:要保存的文件名
             mimeType:要保存到服务器的文件类型
             */
            [formData appendPartWithFileData:imageData name:@"file" fileName:fullPath mimeType:@"image/jpg"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [hub hideAnimated:YES];
            DSLog(@"上传成功");
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [hub hideAnimated:YES];
            DSLog(@"上传失败");
        }];
    

    相关文章

      网友评论

        本文标题:ios ~ (相机、相册)图片发送、上传

        本文链接:https://www.haomeiwen.com/subject/ttywyltx.html