美文网首页iOS高质量博客iOS技术点IOS
iOS AFN上传图片(压缩图片)详细

iOS AFN上传图片(压缩图片)详细

作者: 超_iOS | 来源:发表于2016-04-26 10:02 被阅读2804次

    利用AFN封装上传多张图片方法,并压缩图片体积

    + (void)CommentPicWithDic:(NSDictionary *)dic//上传图片时可能有的附加条件如userid;
                     withImages:(NSDictionary *)imageDic//存图片的字典
                        success:(void (^)(NSDictionary *))success
                          faile:(void (^)(NSError *))faile
    {
        NSString *urlStr = @"上传到的地址";
        AFHTTPRequestOperationManager *Manager = [AFHTTPRequestOperationManager manager];
        Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
        [afManager POST:urlStr parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
            for (id key in imageDic) {
                UIImage *image = [imageDic objectForKey:key];
    //FileData:图片压缩后的data类型
    //name: 后台规定的key
    //fileName:自己给文件起名
    //mimeType :图片类型
                [formData appendPartWithFileData:UIImagePNGRepresentation(image) name:[NSString stringWithFormat:@"%@",key] fileName:[NSString stringWithFormat:@"%@.png",key] mimeType:@"image/png"];
            }
        }success:^(AFHTTPRequestOperation *operation, id responseObject){
           
            success(responseObject);
        }failure:^(AFHTTPRequestOperation *operation, NSError *error){
           
            faile(error);
        }];
    }
    
    if (imgsAry.count != 0){//存图片的数组
                for (int j = 0; j < imgsAry.count; j++) {
                     UIImage * img = imgsAry[j];
                    NSData *imgData = UIImagePNGRepresentation(img);//亚索体积
                    if (imgData.length > 1024000) {//图片不大于1M
                        CGSize imgSize = CGSizeMake(img.size.width / 2, img.size.height / 2);
                        img = [self OriginImage:img scaleToSize:imgSize];//亚索图片尺寸
                    }
                     [imgDic setObject:img forKey:[NSString stringWithFormat:@"aaa%d",j + 1]];//后台让你传的图片对应的key
                }
    //方法使用
    [APIManager CommentPicWithDic:imgInfoDic withImages:imgDic success:^(NSDictionary *info) {
                    NSLog(@"%@",info);
                } faile:^(NSError *error) {
                    NSLog(@"0000%@",error);
                }];
    
    //图片处理,图片压缩
    - (UIImage*)OriginImage:(UIImage *)image scaleToSize:(CGSize)size {
        UIGraphicsBeginImageContext(size);  //你所需要的图片尺寸
        [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
        UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return scaledImage;   //返回已变图片
    }
    

    对您有用的话,可否关注下本人?以此激励我和您的共同提高,谢谢了.

    12.5
    对于太大的图片还是有缺陷,求大神给建议

    3.2
    自问自答.想起来了更新下备忘

    //传图片
    - (void)PostImgWithDic:(NSDictionary *)dic
                   withImg:(NSDictionary *)imgDic
                       url:(NSString *)url
              successBlock:(SuccessBlock)successBlock
              failureBlock:(FailureBlock)failureBlock
    {
    //    AFHTTPSessionManager *manager = [self baseHtppRequest];
        AFHTTPSessionManager *postAvatarManager = [AFHTTPSessionManager manager];
        postAvatarManager.responseSerializer= [AFHTTPResponseSerializer serializer];
        [postAvatarManager POST:url parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            if (imgDic.allKeys.count == 0) {
                NSLog(@"没有图片上传");
            }else
            {
                for (id key in imgDic) {
                    UIImage *image = [imgDic objectForKey:key];
                    
                    NSData *data = [[NSData alloc] init];
                    data = UIImageJPEGRepresentation(image, 1.0);
                    CGFloat count = 100;
                    DLog(@"图片大小%ld",data.length);
                    while (data.length > 1024000) {
                        count--;
                        data =  UIImageJPEGRepresentation(image, count / 100);
                        DLog(@"变化图片大小%ld,%f",data.length,count / 100);
                    }
    
                    
                    [formData appendPartWithFileData: data name:[NSString stringWithFormat:@"%@",key] fileName:[NSString stringWithFormat:@"%@.jpeg",key] mimeType:@"image/jpeg"];//Type:@"image/jpeg"fileName:[NSString stringWithFormat:@"%@.png"
                }
            }
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            nil;
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //        NSLog(@"上传图片成功了AFN ");
            DLog(@"上传图片成功了AFN ");
            successBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSString *errorStr = [error.userInfo objectForKey:@"NSLocalizedDescription"];
    //        NSLog(@"上传图片失败了了AFN ");
            DLog(@"上传图片失败了了AFN ");
            failureBlock(errorStr);
        }];
    }
    
    

    相关文章

      网友评论

      • 卓敦:图片放在字典里面的时候,对应的key值是什么
      • 卓敦:图片为什么放字典里,不是放在数组吗
      • 0d48debc0995:这样压缩图片容易失真啊
        超_iOS:@不安份的渔人 有什么高见

      本文标题:iOS AFN上传图片(压缩图片)详细

      本文链接:https://www.haomeiwen.com/subject/warqrttx.html