更换头像 相机/相册
Posted kingstudy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了更换头像 相机/相册相关的知识,希望对你有一定的参考价值。
// // PicturesTableViewCell.m // WaterProofer // // Created by admin on 2019/9/21. // Copyright © 2019 WaterProofer. All rights reserved. // #import "PicturesTableViewCell.h" @import AVFoundation; @import Photos; @interface PicturesTableViewCell ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate> @end @implementation PicturesTableViewCell - (void)awakeFromNib { [super awakeFromNib]; } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; } - (IBAction)cameraClick:(UIButton *)sender { //调用相册、相机 [self createCameraOrPhotoAlbum]; } #pragma mark -- 调用相机、相册 - (void)createCameraOrPhotoAlbum { __weak typeof(self)wself = self; UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction *action = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [wself createPhotoAlbum]; }]; [alert addAction:action]; UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [wself createCamera]; }]; [alert addAction:action1]; UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { }]; [alert addAction:cancel]; [self.containingViewController presentViewController:alert animated:YES completion:nil]; } - (void)createCamera { [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {//相机权限 if (granted) { UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; picker.allowsEditing = YES; picker.sourceType = UIImagePickerControllerSourceTypeCamera; [self.containingViewController presentViewController:picker animated:YES completion:^{ }]; }else{ [self showRequestErrorTitle:@"请开启相机权限" handler:^(UIAlertAction *action) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; }]; } }]; } #pragma - mark -选中图片 代理方法 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { //得到图片 UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; UIImage *newImage = [self croppedImage:image]; //存入相册 if(picker.sourceType == UIImagePickerControllerSourceTypeCamera) { //存入相册 UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil); } else if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) { } [self uploadImageWithImagePath:newImage];//去保存图片 -》 上传图片 [self.containingViewController dismissViewControllerAnimated:YES completion:^{ }]; } //剪裁图片 - (UIImage *)croppedImage:(UIImage *)image { if (image) { //解决倒像问题 UIGraphicsBeginImageContext(image.size); [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); //裁剪 CGRect rectMAX = CGRectMake((newImage.size.width-newImage.size.height)/2, 0, newImage.size.height, newImage.size.height); CGImageRef subImageRef = CGImageCreateWithImageInRect(newImage.CGImage, rectMAX); UIGraphicsBeginImageContext(rectMAX.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextDrawImage(context, CGRectMake(0, 0, newImage.size.height, newImage.size.height), subImageRef); UIImage *viewImage = [UIImage imageWithCGImage:subImageRef]; UIGraphicsEndImageContext(); CGImageRelease(subImageRef); return viewImage; } return nil; } - (void)createPhotoAlbum { [phphotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { if (status == PHAuthorizationStatusAuthorized){ UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; picker.allowsEditing = YES; picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; [self.containingViewController presentViewController:picker animated:YES completion:^{ }]; }else{ [self showRequestErrorTitle:@"请开启相册权限" handler:^(UIAlertAction *action) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; }]; // UIAlertController *alert = // [UIAlertController alertControllerWithTitle:@"请开启相册权限" // message:@"开启路径:设置>隐私>照片>番茄" // preferredStyle:UIAlertControllerStyleAlert]; // // UIAlertAction *action = // [UIAlertAction actionWithTitle:@"确定" // style:UIAlertActionStyleDefault // handler:nil]; // // [alert addAction:action]; // [self presentViewController:alert animated:YES completion:nil]; } }]; } #pragma mark -- 上传头像 - (void)uploadImageWithImagePath:(UIImage *)image { [self.cameraBtn setImage:image forState:UIControlStateNormal]; __weak typeof(self)weakSelf = self; [[WPApiRequest sharedManager] PostBodyRequestWithActionName:@"" andPramater:@{} andImage:@"" succeeded:^(id _Nonnull responseObject) { }]; } @end
//上传图片 -(void)uploadMostImageWithURLString:(NSString *)URLString parameters:(NSDictionary*)parameters uploadDatas:(NSArray *)uploadDatas uploadName:(NSString *)uploadName success:(void (^)(NSDictionary*dic))success{ //1.管理器 AFHTTPSessionManager* manager = [AFHTTPSessionManager manager]; //2 设定类型 manager.requestSerializer = [AFHTTPRequestSerializer serializer]; manager.responseSerializer = [AFJSONResponseSerializer serializer]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil]; manager.requestSerializer.timeoutInterval = 20.0f; //超时时间 [manager.requestSerializer setValue:@"1" forHTTPHeaderField:@"app_system"]; NSMutableDictionary* postDic = [[NSMutableDictionary alloc]init]; if (parameters) { [postDic addEntriesFromDictionary:parameters]; } [postDic setObject:[ArtLoginData sharedManager].cityID forKey:@"city_id"]; [postDic setObject:[ArtLoginData sharedManager].tokenStr forKey:@"token"]; [postDic setObject:@"2" forKey:@"vtype"]; if (![[parameters allKeys]containsObject:@"phone"]) { [postDic setObject:[ArtLoginData sharedManager].userID forKey:@"phone"]; } if (!(uploadDatas.count>0)) { [postDic setObject:@"" forKey:@"imageurl"]; } NSString *stringurl=[NSString stringWithFormat:@"%@%@",BASEURL,URLString]; [self showHUD]; [manager POST:stringurl parameters:postDic constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData){ /* * 该方法的参数 1. appendPartWithFileData:要上传的照片[二进制流] 2. name:对应网站上[upload.php中]处理文件的字段(比如upload) 3. fileName:要保存在服务器上的文件名 4. mimeType:上传的文件的类型 */ for (int i = 0; i < uploadDatas.count; i++){ UIImage *image = uploadDatas[i]; NSData *imageData = UIImageJPEGRepresentation(image, 0.8); NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyyMMddHHmmss"]; NSString *dateString = [formatter stringFromDate:[NSDate date]]; NSString *fileName = [NSString stringWithFormat:@"%@.jpg", dateString]; [formData appendPartWithFileData:imageData name:uploadName fileName:fileName mimeType:@"image/jpeg"]; } }progress:^(NSProgress * _Nonnull uploadProgress) { }success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { [self hideHUD]; ResultModel *model=[ResultModel yy_modelWithDictionary:responseObject]; if (model.isSuccess) { if(success){ success(responseObject); } }else{ [self showToastWithText:model.msg]; } }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { [self hideHUD]; if (TBReachability){ [self showToastWithText:@"连接服务器失败!"]; }else{ [self showToastWithText:@"请检查网络连接!"]; } }]; }
<key>NSCameraUsageDescription</key>
<string>XXXAPP在上传图片的服务中需要访问您的相机</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>XXXAPP在上传图片的服务中需要访问您的相册</string>
以上是关于更换头像 相机/相册的主要内容,如果未能解决你的问题,请参考以下文章
Bmob云IM实现头像更换并存入Bmob云数据库中(1.拍照替换,2.相册选择)