iOS 图片上传使用base64或者二进制流上传头像功能

 更新时间:2017年09月29日 11:04:16   投稿:mrr  
这篇文章主要介绍了iOS 图片上传使用base64或者二进制流上传头像功能,需要的朋友可以参考下

我们在写代码的时候经常会将头像进行上传服务器,上传头像图片我试过两种方式

一种方式就是使用base64字符串上传图片,这种形式我个人认为比较适合上传图片数量比较少的,比如上传头像,上传图片数量多的话,速度会慢些

另一种方式是使用二进制流进行上传图片,这种方式上传图片少或者数量多都没关系,速度也很快

demo地址: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) {
  [formData appendPartWithFileData: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

总结

以上所述是小编给大家介绍的iOS 图片上传使用base64或者二进制流上传头像功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • IOS开发代码分享之设置UISearchBar的背景颜色

    IOS开发代码分享之设置UISearchBar的背景颜色

    在项目开发中,我们经常要用到UISearchBar,在网上看到了很多关于去除掉他背景色的方法,都已经失效了,今天来分享一个正常使用的方法,希望能帮到大家
    2014-09-09
  • 基于IOS端微信分享失效的踩坑及解决方法

    基于IOS端微信分享失效的踩坑及解决方法

    下面小编就为大家分享一篇基于IOS端微信分享失效的踩坑及解决方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-01-01
  • iOS支付宝使用方法详解

    iOS支付宝使用方法详解

    这篇文章主要为大家详细介绍了iOS支付宝的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-01-01
  • ios12中遇到的带input弹窗的错位问题的解决方法

    ios12中遇到的带input弹窗的错位问题的解决方法

    这篇文章主要介绍了ios12中遇到的带input弹窗的错位问题的解决方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05
  • iOS 开发常用宏总结

    iOS 开发常用宏总结

    这篇文章主要介绍了iOS 开发常用宏总结的相关资料,需要的朋友可以参考下
    2016-09-09
  • 分享一些iOS开发实用的小技巧

    分享一些iOS开发实用的小技巧

    这篇文章主要给大家分享了一些iOS开发实用的小技巧,这些小技巧在大家开发iOS的时候还是相当实用,有需要的朋友们下面来一起看看吧。
    2016-09-09
  • iOS应用内实现跳转到手机淘宝天猫的方法

    iOS应用内实现跳转到手机淘宝天猫的方法

    这篇文章主要给大家介绍了关于iOS应用内如何实现跳转到手机淘宝天猫的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧。
    2017-12-12
  • iOS动画解析之圆球加载动画XLBallLoading的实现

    iOS动画解析之圆球加载动画XLBallLoading的实现

    加载动画对大家来说都不陌生,我们在平时都会遇见,开发中也必不可少,所以下面这篇文章主要给大家介绍了关于iOS动画解析之圆球加载动画XLBallLoading实现的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-11-11
  • iOS动态验证码实现代码

    iOS动态验证码实现代码

    本文通过实例代码给大家介绍了ios动态验证码的实现方法,代码简单易懂,非常不错,具有参考借鉴价值,需要的朋友参考下吧
    2018-04-04
  • iOS中指纹识别常见问题汇总

    iOS中指纹识别常见问题汇总

    最近在公司做了一个app要使用指纹支付的功能,在实现过程中遇到各种坑,今天小编抽抗给大家总结把遇到问题汇总特此分享到脚本之家平台,需要的朋友参考下
    2016-12-12

最新评论