欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2023-12-20 16:07:46
我们在写代码的时候经常会将头像进行上传服务器,上传头像图片我试过两种方式 一种方式就是使用base64字符串上传图片,这种形式我个人认为比较适合上传图片数量比较少的,比如...

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

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

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

demo地址:

demo地址:  https://github.com/tuwanli/picturehead

选择头像效果:

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

程序如下:

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或者二进制流上传头像功能,希望对大家有所帮助

上一篇:

下一篇: