##iOS中修改图片的大小:修改分辨率和裁剪 ###第一步:裁剪图片
// 裁剪// 要裁剪的图片区域,按照原图的像素大小来,超过原图大小的边自动适配CGSize size = CGSizeMake(1000, 1000);UIImage *img = [self imageWithImageSimple:image scaledToSize:size];/*** 要裁剪的图片区域,按照原图的像素大小来,超过原图大小的边自动适配*/
- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size {// 1. 创建一个基于位图(bitmap)的上下文(context), 并将其设置为当前上下文(context)UIGraphicsBeginImageContext(size);// 2. 绘制改变图片的大小[image drawInRect:CGRectMake(0, 0, size.width, size.height)];// 3. 从当前context中创建一个改变大小后的图片UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();// 4. 使当前的context出堆栈UIGraphicsEndImageContext();// 5. 返回新的改变大小后的图片return scaledImage;
}
复制代码
###第二步:压缩图片
NSData *imageData = UIImageJPEGRepresentation(img, 0.001);
复制代码
###第三步:上传图片
// 上传图片[mgr POST:@"http://api.jingshonline.com/api/LawyerCenter/UploadAvatdor" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {// 上传文件NSDateFormatter *formatter = [[NSDateFormatter alloc] init];formatter.dateFormat = @"yyyyMMddHHmmss";NSString *str = [formatter stringFromDate:[NSDate date]];NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];[formData appendPartWithFileData:imageData name:@"avatdor" fileName:fileName mimeType:@"image/png"];} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];userInfo[@"iconURLStr"] = responseObject[@"url"];self.iconURLStr = responseObject[@"url"];[[NSNotificationCenter defaultCenter] postNotificationName:@"updateIconAndName" object:self userInfo:userInfo];[SVProgressHUD showSuccessWithStatus:@"修改成功"];} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {[SVProgressHUD showErrorWithStatus:@"修改失败"];ADLog(@"%@", error);}];
复制代码