我们在写代码的时候经常会将头像进行上传服务器,上传头像图片我试过两种方式
一种方式就是使用base64字符串上传图片,这种形式我个人认为比较适合上传图片数量比较少的,比如上传头像,上传图片数量多的话,速度会慢些
另一种方式是使用二进制流进行上传图片,这种方式上传图片少或者数量多都没关系,速度也很快
demo地址:http://download.csdn.net/detail/tuwanli125/9340205
demo地址: https://github.com/tuwanli/PictureHead
选择头像效果:
程序如下:
ViewController.h
1
2
3
4
5
|
# import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutletUIImageView *headIcon;
- (IBAction)changeIconAction:(UITapGestureRecognizer *)sender;
@end
|
ViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
|
# 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或者二进制流上传头像功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:http://blog.csdn.net/qq_33226881/article/details/78130116