ios 实现图片上传的2种方式

项目中要用到图片上传,开始最早用到的是方式是把image图片转为data 数据,然后用afnetwork 方式上传,后来这个方式改掉,有用到了以文件的形式上传给服务器,2个种方式,文件形式上传比较好点,下面提供所需的大致代码,

第一步先获取图片,相册或者拍照都可以得到图片,然后把图片存datas里,然后发送请求,使用的都是afnetwork自带的方法

//postParameters 数据放到value 里面
NSMutableDictionary* postParameters = [NSMutableDictionary dictionary];
    [datas enumerateObjectsUsingBlock:^(NSString* base64String, NSUInteger idx, BOOL *stop) {
        NSString* key = [@"image" stringByAppendingFormat:@"%lu", (unsigned long)idx + 1];
        //图片都base64 转码,然后放倒value
        postParameters[key] = base64String;
    }];

 NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:"url地址" parameters:postParameters error:NULL];
    [request setTimeoutInterval:30];
    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        @try {

            NSString* json = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            success(operation, json.JSONValue);

        } @catch(NSException* exception) {
            failure(operation, @"数据错误");
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                failure(operation, error.localizedDescription);
            }
        }
    }];

这就是简单的data 上传图片,

第二张方式就是图片地址的形式上传图片
同样的方法先是把图片获取到存到沙盒,然后获取地址,具体代码如下

        //写入到沙盒,存地址
        [photos enumerateObjectsUsingBlock:^(OrderBaskPhoto* photo, NSUInteger idx, BOOL *stop) {
            NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString* totalPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%lu.jpg",(unsigned long)idx]];
            [photo.data writeToFile:totalPath atomically:NO];
             photo.imagePath=totalPath;
            [datas addObject:photo.imagePath];
        }];

 // 同样要把图片地址转为key-value ,放入字典中
 NSMutableDictionary* postParameters = [NSMutableDictionary dictionary];
    [datas enumerateObjectsUsingBlock:^(NSString* pathString, NSUInteger idx, BOOL *stop) {
        NSString* key = [@"image" stringByAppendingFormat:@"%lu", (unsigned long)idx + 1];
        postParameters[key] = [NSURL fileURLWithPath:pathString];
    }];

然后调用afnetwork 方法

 NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:"url地址" parameters:postParameters error:NULL];
    [request setTimeoutInterval:30];

    AFHTTPRequestOperation *operation=[self POST:urlString  parameters:mparameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    // 这快需要获取图片的本地地址,然后放入formdata中,    
        [postParameters enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSURL *value, BOOL *stop) {

            [formData appendPartWithFileURL:value name:key error:nil];
        }];


    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

        @try {
            NSString* json = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            success(operation, json.JSONValue);
        } @catch(NSException* exception) {
            failure(operation, @"数据错误");
        }


    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         failure(operation, error.localizedDescription);
    }];

这样就可以上传图片了,以上就是简单的两种方式上图图片,
在上上传的时候图片有限制,图片需要压缩,所以图片压缩的代码也贴一下

//需要的设置常量
static const NSUInteger kMaxFeedbackTextLength = 200;
static const CGFloat kImageShorterEdgeUppderBound = 720;

//图片处理
- (void)processOriginalImages:(NSArray*)originalImages
{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self showLoading:nil interactonEnabled:NO];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        __block BOOL illegalImageSelected = NO;

        [originalImages enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(NSDictionary* dic, NSUInteger idx, BOOL *stop) {

            UIImage* image = dic[UIImagePickerControllerOriginalImage];
            if (MAX(image.size.width, image.size.height) / MIN(image.size.width, image.size.height) <= 5) {
                CGSize size = image.size;
                if (MIN(image.size.width, image.size.height) > kImageShorterEdgeUppderBound) {
                    if (image.size.width < image.size.height) {
                        size = CGSizeMake(kImageShorterEdgeUppderBound, (kImageShorterEdgeUppderBound / image.size.width) * image.size.height);
                    } else {
                        size = CGSizeMake((kImageShorterEdgeUppderBound / image.size.height) * image.size.width, kImageShorterEdgeUppderBound);
                    }
                } else {

                }
                //压缩图片方法
                image = [image fixOrientationWithSize:size];
                NSData* data = UIImageJPEGRepresentation(image, 0.8);


                OrderBaskPhoto* photo = [[OrderBaskPhoto alloc] init];
                photo.data = data;
                //设置缩略图,位图方法
                photo.thumbnail = [Utility imageWithImage:image scaledToFillSize:CGSizeMake(80, 80)];
                [photos addObject:photo];

            } else {
                illegalImageSelected = YES;
            }
        }];

        dispatch_sync(dispatch_get_main_queue(), ^{
            NSParameterAssert(photos.count <= kMaxImageCount);
            if (illegalImageSelected) {
                UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"为保证图片浏览体验,请上传高:宽小于等于5的图片" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }

            [self dismissLoading];
        });
    });
}

上面用到的方法

//压缩图片的方法
@implementation UIImage (fixOrientation)

- (UIImage *)fixOrientationWithSize:(CGSize)size {

    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;

    // No-op if the orientation is already correct
    if (self.imageOrientation != UIImageOrientationUp) {

        switch (self.imageOrientation) {
            case UIImageOrientationDown:
            case UIImageOrientationDownMirrored:
                transform = CGAffineTransformTranslate(transform, size.width, size.height);
                transform = CGAffineTransformRotate(transform, M_PI);
                break;

            case UIImageOrientationLeft:
            case UIImageOrientationLeftMirrored:
                transform = CGAffineTransformTranslate(transform, size.width, 0);
                transform = CGAffineTransformRotate(transform, M_PI_2);
                break;

            case UIImageOrientationRight:
            case UIImageOrientationRightMirrored:
                transform = CGAffineTransformTranslate(transform, 0, size.height);
                transform = CGAffineTransformRotate(transform, -M_PI_2);
                break;
            case UIImageOrientationUp:
            case UIImageOrientationUpMirrored:
                break;
        }

        switch (self.imageOrientation) {
            case UIImageOrientationUpMirrored:
            case UIImageOrientationDownMirrored:
                transform = CGAffineTransformTranslate(transform, size.width, 0);
                transform = CGAffineTransformScale(transform, -1, 1);
                break;

            case UIImageOrientationLeftMirrored:
            case UIImageOrientationRightMirrored:
                transform = CGAffineTransformTranslate(transform, size.height, 0);
                transform = CGAffineTransformScale(transform, -1, 1);
                break;
            case UIImageOrientationUp:
            case UIImageOrientationDown:
            case UIImageOrientationLeft:
            case UIImageOrientationRight:
                break;
        }
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, size.width, size.height,
                                             CGImageGetBitsPerComponent(self.CGImage), 0,
                                             CGImageGetColorSpace(self.CGImage),
                                             CGImageGetBitmapInfo(self.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,size.height,size.width), self.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,size.width,size.height), self.CGImage);
            break;
    }

    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
//图片等比例缩放
+(UIImage *)imageWithImage:(UIImage *)image scaledToFillSize:(CGSize)size
{
    CGFloat scale = MAX(size.width/image.size.width, size.height/image.size.height);
    CGFloat width = image.size.width * scale;
    CGFloat height = image.size.height * scale;
    CGRect imageRect = CGRectMake((size.width - width)/2.0f,
                                  (size.height - height)/2.0f,
                                  width,
                                  height);

    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    [image drawInRect:imageRect];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

以上就是在工作中实现上传图片的过程,谢谢

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值