资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

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

创新互联建站成立于2013年,先为罗庄等服务建站,罗庄等地企业,进行企业商务咨询服务。为罗庄企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

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

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

demo地址:http://download.csdn.net/detail/tuwanli125/9340205

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

选择头像效果:

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

程序如下:

ViewController.h

#import 
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutletUIImageView *headIcon;
- (IBAction)changeIconAction:(UITapGestureRecognizer *)sender;
@end

ViewController.m

#import "ViewController.h"
#import "AFHTTPRequestOperationManager.h"
@interface ViewController ()
{
 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 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或者二进制流上传头像功能
本文链接:http://www.cdkjz.cn/article/gjhioc.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220