iOS-图片上传的两种方式

<p>
我们在写代码的时候经常会将头像进行上传服务器,上传头像图片我试过两种方式
一种方式就是使用base64字符串上传图片,这种形式我个人认为比较适合上传图片数量比较少的,比如上传头像,上传图片数量多的话,速度会慢些
另一种方式是使用二进制流进行上传图片,这种方式上传图片少或者数量多都没关系,速度也很快
</p>
demo地址http://download.csdn.net/detail/tuwanli125/9340205](http://download.csdn.net/detail/tuwanli125/9340205)
demo地址:https://github.com/tuwanli/PictureHead

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutletUIImageView *headIcon;
- (IBAction)changeIconAction:(UITapGestureRecognizer *)sender;
@end

ViewController.m

#import "ViewController.h"
#import "AFHTTPRequestOperationManager.h"
@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
{

   UIImagePickerController *pickerController;
    AFHTTPRequestOperationManager *manager;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [superviewDidLoad];
    //初始化头像控件
    [selfinitHeadIcon];
    //初始化pickController
    [selfcreateData];
}
- (void)initHeadIcon
{

    self.view.backgroundColor = [UIColorlightGrayColor];
    self.headIcon.layer.cornerRadius = self.headIcon.frame.size.height/2;
    self.headIcon.clipsToBounds =YES;
    self.headIcon.layer.borderColor = [UIColor whiteColor].CGColor;
    self.headIcon.layer.borderWidth = 3;
}
- (void)createData
{
    //初始化pickerController
    pickerController = [[UIImagePickerControlleralloc]init];
    pickerController.view.backgroundColor = [UIColororangeColor];
    pickerController.delegate =self;
    pickerController.allowsEditing =YES;
}

- (IBAction)changeIconAction:(UITapGestureRecognizer *)sender {
    UIActionSheet *actionSheet = [[UIActionSheetalloc]initWithTitle:@"选择头像"delegate:selfcancelButtonTitle:@"取消"destructiveButtonTitle:nilotherButtonTitles:@"拍照",@"相册",@"图库",nil];
    [actionSheet showInView:[UIApplicationsharedApplication].keyWindow];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
   if (buttonIndex ==0) {//相机
       if([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
           NSLog(@"支持相机");
            [selfmakePhoto];
        }else{
            UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"请在设置-->隐私-->相机,中开启本应用的相机访问权限!!"delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"我知道了",nil];
            [alertshow];
        }
    }elseif (buttonIndex ==1){//相片
       if([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
           NSLog(@"支持相册");
            [selfchoosePicture];
        }else{
            UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"请在设置-->隐私-->照片,中开启本应用的相机访问权限!!"delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"我知道了",nil];
            [alertshow];
        }
    }elseif (buttonIndex ==2){//图册
        if([UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum])
        {
           NSLog(@"支持图库");
            [selfpictureLibrary];
//            [self presentViewController:picker animated:YES completion:nil];
        }else{
            UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"请在设置-->隐私-->照片,中开启本应用的相机访问权限!!"delegate:selfcancelButtonTitle:@"取消"otherButtonTitles:@"我知道了",nil];
            [alertshow];
        }
    }elseif (buttonIndex ==3){
        
    }

}
//跳转到imagePicker里
- (void)makePhoto
{
    pickerController.sourceType =UIImagePickerControllerSourceTypeCamera;
    [selfpresentViewController:pickerControlleranimated:YEScompletion:nil];
}
//跳转到相册
- (void)choosePicture
{
    pickerController.sourceType =UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [selfpresentViewController:pickerControlleranimated:YEScompletion:nil];
}
//跳转图库
- (void)pictureLibrary
{
    pickerController.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
    [selfpresentViewController:pickerControlleranimated:YEScompletion:nil];
}
//用户取消退出picker时候调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
   NSLog(@"%@",picker);
    [pickerControllerdismissViewControllerAnimated:YEScompletion:^{
        
    }];
}
//用户选中图片之后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
   NSLog(@"%s,info == %@",__func__,info);
    
    UIImage *userImage = [selffixOrientation:[infoobjectForKey:@"UIImagePickerControllerOriginalImage"]];
    
    userImage = [selfscaleImage:userImagetoScale:0.3];
    
    //保存图片
//    [self saveImage:userImage name:@"某个特定标示"];
    
    [pickerControllerdismissViewControllerAnimated:YEScompletion:^{
        
        
    }];
    [self.headIconsetImage:userImage];
    self.headIcon.contentMode = UIViewContentModeScaleAspectFill;
    self.headIcon.clipsToBounds =YES;
    //照片上传
    [selfupDateHeadIcon:userImage];
}

- (void)upDateHeadIcon:(UIImage *)photo
{
    //两种方式上传头像
    /*方式一:使用NSData数据流传图片*/
   NSString *imageURl =@"";
    manager.responseSerializer = [AFHTTPResponseSerializerserializer];
    
    manager.responseSerializer.acceptableContentTypes =[NSSetsetWithObject:@"text/html"];
    [managerPOST:imageURlparameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formDataappendPartWithFileData:UIImageJPEGRepresentation(photo,1.0)name:@"text"fileName:@"test.jpg"mimeType:@"image/jpg"];
        
    }success:^(AFHTTPRequestOperation *operation,id responseObject) {
        
    }failure:^(AFHTTPRequestOperation *operation,NSError *error) {
        
    }];
    /*方式二:使用Base64字符串传图片*/
    NSData *data =UIImageJPEGRepresentation(photo,1.0);
    
   NSString *pictureDataString=[database64Encoding];
    NSDictionary * dic  =@{@"verbId":@"modifyUserInfo",@"deviceType":@"ios",@"userId":@"",@"photo":pictureDataString,@"mobileTel":@""};
    [managerPOST:@""parameters:dic success:^(AFHTTPRequestOperation *operation,idresponseObject) {
       if ([[responseObjectobjectForKey:@"flag"]intValue] == 0) {
            
        }else{
            
        }
    }
         failure:^(AFHTTPRequestOperation *operation,NSError *error) {
          }];
}
//保存照片到沙盒路径(保存)
- (void)saveImage:(UIImage *)image name:(NSString *)iconName
{
    NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    //写入文件
   NSString *icomImage = iconName;
    NSString *filePath = [[pathsobjectAtIndex:0]stringByAppendingPathComponent:[NSStringstringWithFormat:@"%@.png", icomImage]];
    // 保存文件的名称
    //    [[self getDataByImage:image] writeToFile:filePath atomically:YES];
    [UIImagePNGRepresentation(image)writeToFile: filePath atomically:YES];
}
//缩放图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
   UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [imagedrawInRect:CGRectMake(0,0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSLog(@"%@",NSStringFromCGSize(scaledImage.size));
   return scaledImage;
}
//修正照片方向(手机转90度方向拍照)
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation ==UIImageOrientationUp)
       return aImage;

    CGAffineTransform transform =CGAffineTransformIdentity;
    
   switch (aImage.imageOrientation) {
        caseUIImageOrientationDown:
        caseUIImageOrientationDownMirrored:
            transform =CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform =CGAffineTransformRotate(transform,M_PI);
           break;
            
        caseUIImageOrientationLeft:
        caseUIImageOrientationLeftMirrored:
            transform =CGAffineTransformTranslate(transform, aImage.size.width,0);
            transform =CGAffineTransformRotate(transform,M_PI_2);
           break;
            
        caseUIImageOrientationRight:
        caseUIImageOrientationRightMirrored:
            transform =CGAffineTransformTranslate(transform,0, aImage.size.height);
            transform =CGAffineTransformRotate(transform, -M_PI_2);
           break;
       default:
           break;
    }
    
   switch (aImage.imageOrientation) {
        caseUIImageOrientationUpMirrored:
        caseUIImageOrientationDownMirrored:
            transform =CGAffineTransformTranslate(transform, aImage.size.width,0);
            transform =CGAffineTransformScale(transform, -1,1);
           break;
            
        caseUIImageOrientationLeftMirrored:
        caseUIImageOrientationRightMirrored:
            transform =CGAffineTransformTranslate(transform, aImage.size.height,0);
            transform =CGAffineTransformScale(transform, -1,1);
           break;
       default:
           break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
   CGContextRef ctx =CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                            CGImageGetBitsPerComponent(aImage.CGImage),0,
                                            CGImageGetColorSpace(aImage.CGImage),
                                            CGImageGetBitmapInfo(aImage.CGImage));
   CGContextConcatCTM(ctx, transform);
   switch (aImage.imageOrientation) {
        caseUIImageOrientationLeft:
        caseUIImageOrientationLeftMirrored:
        caseUIImageOrientationRight:
        caseUIImageOrientationRightMirrored:
           CGContextDrawImage(ctx,CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
           break;
            
       default:
           CGContextDrawImage(ctx,CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
           break;
    }

    CGImageRef cgimg =CGBitmapContextCreateImage(ctx);
   UIImage *img = [UIImageimageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
   return img;
}

此demo从相册选区图片使用的单选图片,如果想看多选图片显示在ScrollView中demo 地址:https://github.com/tuwanli/PictureMutipleSelect

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,082评论 5 464
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,231评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,047评论 0 327
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,977评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,893评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,014评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,976评论 3 388
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,605评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,888评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,906评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,732评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,513评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,980评论 3 301
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,132评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,447评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,027评论 2 343
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,232评论 2 339

推荐阅读更多精彩内容