- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *newImage = [info[UIImagePickerControllerEditedImage] scaleToFitSizeIfNeed:CGSizeMake(1280.0f, 1280.0f)];
NSData *data = UIImageJPEGRepresentation(newImage, 0.5f);
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"avatar.jpg"];
[data writeToFile:path atomically:YES];
NSString *URL = [NSString stringWithFormat:@"%@%@",URL_HEAD,@"file/upload"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];//设置服务器允许的请求格式内容
[manager POST:URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFileData:data name:@"file" fileName:@"avatar.jpg" mimeType:@"image/jpg"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:@"user/changeAvatar" forKey:HSOBJ_URL];
[dic setObject:JSON[@"file_name"] forKey:@"file_name"];
dic = [[HSNetUrlProcess createCompDictWithParm:dic] mutableCopy];
[AFNetworkTool HVDataCache:dic NetBlock:^(NSDictionary *json) {
FLLoginDataModel * currentUser = [FLLoginDataModel mj_objectWithKeyValues:json];
currentUser.isLogin = YES;
[currentUser saveCurrentUser];
[SVProgressHUD showSuccessWithStatus:@"头像修改成功"];
[self.navigationController popViewControllerAnimated:YES];
} ErrorCode:^(int errorCode) {
} Fail:^{
} Setting:nil];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
});
[self dismissViewControllerAnimated:YES completion:nil];
}
更改图片的size(用于限制上传图片大小)
UIImage+PPCategory.h(下面的方法在这里)
- (UIImage *)scaleToFitSizeIfNeed:(CGSize)bounds
{
CGFloat factor1 = bounds.width/self.size.width;
CGFloat factor2 = bounds.height/self.size.height;
CGFloat factor = MIN(factor1, factor2);
if (factor >= 1) {
return self;
}
// return [self scaleByFactor:factor];
CGFloat resultWidth = self.size.width * factor;
CGFloat resultHeight = self.size.height * factor;
return [self scaleToSize:CGSizeMake(resultWidth, resultHeight)];
}