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

发布时间 - 2026-01-11 03:28:41    点击率:

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

一种方式就是使用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  # 图片上传  # base64  # iOS实现相册多选图片上传功能  # 详解IOS开发中图片上传时两种图片压缩方式的比较  # 移动端html5图片上传方法【更好的兼容安卓IOS和微信】  # iOS实现压缩图片上传功能  # 微信JSSDK多图片上传并且解决IOS系统上传一直加载的问题  # iOS实现录音转码MP3及转码BASE64上传示例  # 上传图片  # 上传  # 请在  # 我知道了  # 两种  # 访问权限  # 小编  # 跳转到  # 流进  # 数量多  # 在此  # 都没  # 给大家  # 想看  # 跳转  # 会将  # 试过  # 所述  # 回调  # 给我留言 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Win11怎么设置虚拟桌面 Win11新建多桌面切换操作【技巧】  Swift中switch语句区间和元组模式匹配  google浏览器怎么清理缓存_谷歌浏览器清除缓存加速详细步骤  千库网官网入口推荐 千库网设计创意平台入口  Laravel如何实现API资源集合?(Resource Collection教程)  西安专业网站制作公司有哪些,陕西省建行官方网站?  免费网站制作appp,免费制作app哪个平台好?  Laravel如何理解并使用服务容器(Service Container)_Laravel依赖注入与容器绑定说明  Python并发异常传播_错误处理解析【教程】  如何在局域网内绑定自建网站域名?  制作网站软件推荐手机版,如何制作属于自己的手机网站app应用?  html5怎么画眼睛_HT5用Canvas或SVG画眼球瞳孔加JS控制动态【绘制】  Laravel怎么调用外部API_Laravel Http Client客户端使用  如何使用 jQuery 正确渲染 Instagram 风格的标签列表  如何在阿里云虚拟机上搭建网站?步骤解析与避坑指南  ,怎么在广州志愿者网站注册?  如何用搬瓦工VPS快速搭建个人网站?  WEB开发之注册页面验证码倒计时代码的实现  Laravel如何创建自定义中间件?(Middleware代码示例)  laravel怎么在请求结束后执行任务(Terminable Middleware)_laravel Terminable Middleware请求结束任务执行方法  Laravel如何配置.env文件管理环境变量_Laravel环境变量使用与安全管理  如何在 React 中条件性地遍历数组并渲染元素  如何在橙子建站中快速调整背景颜色?  移动端手机网站制作软件,掌上时代,移动端网站的谷歌SEO该如何做?  HTML5空格和nbsp有啥关系_nbsp的作用及使用场景【说明】  Laravel Eloquent关联是什么_Laravel模型一对一与一对多关系精讲  中国移动官方网站首页入口 中国移动官网网页登录  香港服务器建站指南:外贸独立站搭建与跨境电商配置流程  Laravel如何实现邮箱地址验证功能_Laravel邮件验证流程与配置  大型企业网站制作流程,做网站需要注册公司吗?  Win11怎么关闭资讯和兴趣_Windows11任务栏设置隐藏小组件  HTML透明颜色代码怎么让图片透明_给img元素加透明色的技巧【方法】  Laravel如何处理JSON字段_Eloquent原生JSON字段类型操作教程  百度浏览器网页无法复制文字怎么办 百度浏览器复制修复  javascript基于原型链的继承及call和apply函数用法分析  成都品牌网站制作公司,成都营业执照年报网上怎么办理?  如何用PHP快速搭建CMS系统?  Win11怎样安装网易有道词典_Win11安装词典教程【步骤】  Laravel如何设置定时任务(Cron Job)_Laravel调度器与任务计划配置  Laravel如何使用Vite进行前端资源打包?(配置示例)  Laravel怎么进行数据库回滚_Laravel Migration数据库版本控制与回滚操作  Laravel用户密码怎么加密_Laravel Hash门面使用教程  如何解决hover在ie6中的兼容性问题  JS去除重复并统计数量的实现方法  iOS正则表达式验证手机号、邮箱、身份证号等  关于BootStrap modal 在IOS9中不能弹出的解决方法(IOS 9 bootstrap modal ios 9 noticework)  如何确认建站备案号应放置的具体位置?  Laravel如何使用集合(Collections)进行数据处理_Laravel Collection常用方法与技巧  详解Nginx + Tomcat 反向代理 如何在高效的在一台服务器部署多个站点  Laravel如何优化应用性能?(缓存和优化命令)