图片上传主要有两种方式,一种是转成Base64,另外一种是二进制流上传
1.二进制流上传
用PPNetworkHelp第三方上传时可以同时上传多张图片,但如果缺点是无法确认哪张照片上传失败,所以简单做了修改,每次上传一张图片,迭代调用。
//加入SSS毫秒图片名称更长,但能更好的避免文件重名。
for (NSUInteger i = 0; i < images.count; i++) {
// 图片经过等比压缩后得到的二进制文件
NSData *imageData = UIImageJPEGRepresentation(images[i], imageScale ?: 1.f);
// 默认图片的文件名, 若fileNames为nil就使用
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmssSSS";
NSString *str = [formatter stringFromDate:[NSDate date]];
//NSLog(@"===%@",str);
NSString *imageFileName = NSStringFormat(@"%@%ld.%@",str,i,imageType?:@"jpg");
[formData appendPartWithFileData:imageData
name:name
fileName:fileNames ? NSStringFormat(@"%@.%@",fileNames[i],imageType?:@"jpg") : imageFileName
mimeType:NSStringFormat(@"image/%@",imageType ?: @"jpg")];
}
[PPNetworkHelper uploadImagesWithURL: @"http://192.168.0.117/device/ImgDemo/getImageDemo"
parameters:@{}
name:@"photo[]"
images: @[self.photoArr[_currentIndex]]
fileNames:nil
imageScale:0.3
imageType:@"jpg"
progress:^(NSProgress *progress) {
//1. png后缀的图片也可以jpg形式上传成功
//2. 回调方法中加入了自动释放池
//3. 递归调用可以显示每张图片的上传情况
//进度
//NSLog(@"==%@",progress);
//NSLog(@"%lld",progress.completedUnitCount);
//NSLog(@"%lld",progress.totalUnitCount);
NSLog(@"%.2f",progress.fractionCompleted);
}
success:^(id responseObject) {
[self continueUpLoadImageWithisSuccess:YES];
}
failure:^(NSError *error) {
[self continueUpLoadImageWithisSuccess:NO];
}];
}
递代调用
- (void)continueUpLoadImageWithisSuccess:(BOOL)isSuccess{
//如果上传失败,并且没有超过最大上传次数,重新上传
if (!isSuccess) {
self.onceFailedCount++;
if (self.onceFailedCount < kMaxUploadCount) {
[self upLoadImage];
return;
}else{
[self.failedIndexs addObject:[NSString stringWithFormat:@"%ld", self.currentIndex]];
}
}
[SVProgressHUD showProgress:(CGFloat)self.currentIndex/self.photoArr.count];
//清空失败次数
self.onceFailedCount = 0;
//记录新的下标index++
self.currentIndex++;
//判断是否上传完毕
if (self.currentIndex == self.photoArr.count) {
//如果是已经上传完了,结束
if (self.failedIndexs.count != 0) {
NSMutableString *mutableString = [NSMutableString string];
for (NSString *index in self.failedIndexs) {
[mutableString appendFormat:@"第%@张",index];
}
[SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@上传失败",mutableString]];
}else{
[SVProgressHUD showSuccessWithStatus:@"图片全部上传成功"];
}
}else{
//如果还没上传完成,继续下一次上传
[self upLoadImage];
}
}
2. Base64方式
图片转成Base64字符串
- (NSString*)imageToString:(UIImage*)image{
if (!image) {
return @"";
}
NSString *mineType = nil;
if (UIImageJPEGRepresentation(image, 1)) {
mineType = @"image/jpg";
}else{
mineType = @"image/png";
}
NSData *data = [self resetSizeOfImageData:image maxSize:100];
NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSString *headString =[NSString stringWithFormat:@"data:%@;base64,",mineType];
return [headString stringByAppendingString:encodedImageStr];
}
如果对图片压缩效果不满意,可以进行再次压缩
//对图片再次压缩
- (NSData *)resetSizeOfImageData:(UIImage *)source_image maxSize:(NSInteger)maxSize
{
//先调整分辨率
CGSize newSize = CGSizeMake(source_image.size.width, source_image.size.height);
CGFloat tempHeight = newSize.height / 1024;
CGFloat tempWidth = newSize.width / 1024;
if (tempWidth > 1.0 && tempWidth > tempHeight) {
newSize = CGSizeMake(source_image.size.width / tempWidth, source_image.size.height / tempWidth);
}
else if (tempHeight > 1.0 && tempWidth < tempHeight){
newSize = CGSizeMake(source_image.size.width / tempHeight, source_image.size.height / tempHeight);
}
UIGraphicsBeginImageContext(newSize);
[source_image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//调整大小
NSData *imageData;
if (UIImagePNGRepresentation(newImage)) {
imageData = UIImagePNGRepresentation(newImage);
}else{
imageData = UIImageJPEGRepresentation(newImage, 0.001);
}
NSUInteger sizeOrigin = [imageData length];//字节长度Byte
NSUInteger sizeOriginKB = sizeOrigin / 1024;
NSLog(@"%ld",sizeOriginKB);
if (sizeOriginKB > maxSize) {
//如果 压缩后还不满意,则再度压缩
NSData *finallImageData ;
if (UIImageJPEGRepresentation(newImage, 0.0001)) {
finallImageData = UIImageJPEGRepresentation(newImage, 0.0001);
}else{
finallImageData = UIImagePNGRepresentation(newImage);
}
NSLog(@"%ld",finallImageData.length/1024);
return finallImageData;
}
return imageData;
}