iOS 圖片上傳使用base64或者二進位制流上傳頭像
我們在寫程式碼的時候經常會將頭像進行上傳伺服器,上傳頭像圖片我試過兩種方式
一種方式就是使用base64字串上傳圖片,這種形式我個人認為比較適合上傳圖片數量比較少的,比如上傳頭像,上傳圖片數量多的話,速度會慢些
另一種方式是使用二進位制流進行上傳圖片,這種方式上傳圖片少或者數量多都沒關係,速度也很快
選擇頭像效果:
程式如下:
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutletUIImageView
- (IBAction)changeIconAction:(UITapGestureRecognizer *)sender;
@end
ViewController.m
#import "ViewController.h"
#import "AFHTTPRequestOperationManager.h"
@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
{
UIImagePickerController
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 = [UIColorwhiteColor].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,id responseObject) {
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;
}