一 图片上传方式有两种:
1.base64字符串形式上传图片,这种方式适合图片数量比较少的时候使用,例如上传用户头像, 因为图片较多时速度会变慢
2.二进制流上传图片 这种方式对于图片数量没有要求
二 上传方法
AFNetworking 方式下:
- (void)uploadImageWithImage:(UIImage*)image {
/*********************************** base64 字符串上传 ************************************************/
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.requestSerializer = [AFHTTPRequestSerializer serializer]; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 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]; [managerPOST:@"" parameters:nil constructingBodyWithBlock:^(id _Nonnull formData) {
//单张图片
NSData *imageData = UIImageJPEGRepresentation(image, 0.7); [formData appendPartWithFileData:imageData name:@"user_icon" fileName:@"userPhoto.jpg" mimeType:@"image/jpg"];
/*-------------------------------------------------*/
//多张图片
NSArray *imagesArray = @[image,image,image,image];
for(NSInteger i = 0; i < imagesArray.count; i++) {
//取出单张图片二进制数据
UIImage *uploadImage = imagesArray[i]; /
/取出单张图片二进制数据 NSData * imageData = UIImageJPEGRepresentation(uploadImage, 0.7);
// 上传的参数名,在服务器端保存文件的文件夹名
NSString * Name = @"user_icon"; // 上传filename
NSString * fileName = [NSString stringWithFormat:@"userPhoto%.2ld.jpg",i];
[formData appendPartWithFileData:imageData name:Name fileName:fileName mimeType:@"image/jpg"];
}
}progress:^(NSProgress*_NonnulluploadProgress) {
}success:^(NSURLSessionDataTask*_Nonnulltask,id _NullableresponseObject) {
}failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror) {
}]; /*********************************** 文件二进制流上传 ************************************************/
NSData*imageData =UIImageJPEGRepresentation(image,0.7);
NSString *imgeStr = [imageData base64EncodedStringWithOptions:NSUTF8StringEncoding];
NSDictionary*params =@{@"user_icon":imgeStr};
[managerPOST:@"192.168.0.11/User/user_icon"parameters:paramsprogress:^(NSProgress*_NonnulluploadProgress) {
}
success:^(NSURLSessionDataTask*_Nonnulltask,id _NullableresponseObject) {
}failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror) {
}];
}
三 图片处理
1.图片压缩
//图片size修改
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize { UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize)); [image drawInRect:CGRectMake(0,0, image.size.width * scaleSize, image.size.height *scaleSize)]; UIImage *scaledImage =UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSLog(@"%@",NSStringFromCGSize(scaledImage.size)); return scaledImage;
}
//图片质量压缩
NSData *data = UIImageJPEGRepresentation(image, 0.5);
image 图片 ;0.5 压缩图片质量比例。
UIImage *resultImage = [UIImage imageWithData:data];