标签:
添加MobileCoreServices.framework
//引用头文件
#import <MobileCoreServices/MobileCoreServices.h>
//修改按钮事件
-(void)clickModifyBtn:(UIButton *)btn
{
UIActionSheet* actionSheet = [[UIActionSheet alloc]
initWithTitle:@"请选择文件来源"
delegate:self
cancelButtonTitle:@"取消"
destructiveButtonTitle:nil
otherButtonTitles:@"照相机",@"本地相簿",nil];
[actionSheet showInView:self.view];
}
#pragma mark - UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
switch (buttonIndex) {
case 0://照相机
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.allowsEditing = YES;
imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:imagePicker animated:YES completion:nil];
}
break;
case 1://本地相簿
{
UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
imagePicker.delegate = self;
imagePicker.allowsEditing = YES;
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:imagePicker animated:YES completion:nil];
}
break;
default:
break;
}
}
#pragma mark - UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
[self performSelector:@selector(saveImage:) withObject:img afterDelay:0.5];
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YES completion:nil];
}
//保存图片
- (void)saveImage:(UIImage *)image {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageFilePathTemp = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
[_imageFilePath setString:imageFilePathTemp];
success = [fileManager fileExistsAtPath:_imageFilePath];
if(success) {
success = [fileManager removeItemAtPath:_imageFilePath error:&error];
}
UIImage *smallImage = [PublicMethod thumbnailWithImageWithoutScale:image size:CGSizeMake(80, 80)];
[UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:_imageFilePath atomically:YES];//写入文件
[self forUpDataRequest];
}
//修改图片大小
+ (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
UIImage *newimage;
if (nil == image) {
newimage = nil;
}
else{
CGSize oldsize = image.size;
CGRect rect;
if (asize.width/asize.height > oldsize.width/oldsize.height) {
rect.size.width = asize.height*oldsize.width/oldsize.height;
rect.size.height = asize.height;
rect.origin.x = (asize.width - rect.size.width)/2;
rect.origin.y = 0;
}
else{
rect.size.width = asize.width;
rect.size.height = asize.width*oldsize.height/oldsize.width;
rect.origin.x = 0;
rect.origin.y = (asize.height - rect.size.height)/2;
}
UIGraphicsBeginImageContext(asize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
[image drawInRect:rect];
newimage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
return newimage;
}
//上传头像图片
-(void)forUpDataRequest
{
//urlStr请求网址
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
[self setRequest:request];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if(data != nil)
{
id object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
dispatch_sync(dispatch_get_main_queue(), ^{
if([[object objectForKey:@"login"]integerValue])
{
UIImage *selfPhoto = [UIImage imageWithContentsOfFile:_imageFilePath];//读取图片文件
self.headSculpture.image = selfPhoto;
}
});
}
else
{
NSLog(@"%@", connectionError.localizedDescription);
UIAlertView * errorAlert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络请求失败,请重试!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[errorAlert show];
}
}];
}
//拼接图片上传请求
- (void)setRequest:(NSMutableURLRequest *)request
{
//分界线的标识符
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//分界线 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
//要上传的图片
NSData* data;
if(_imageFilePath){
UIImage *image=[UIImage imageWithContentsOfFile:_imageFilePath];
//判断图片是不是png格式的文件
if (UIImagePNGRepresentation(image)) {
//返回为png图像。
data = UIImagePNGRepresentation(image);
}else {
//返回为JPEG图像。
data = UIImageJPEGRepresentation(image, 1.0);
}
}
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
//添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//添加字段名称,换2行
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"key"];
//添加字段的值
[body appendFormat:@"%@\r\n",_keykey];
////添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
[body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"file",_imageFilePath];
//声明上传文件的格式
[body appendFormat:@"Content-Type: image/jpge, image/pjpeg \r\n\r\n"];
//声明结束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData=[NSMutableData data];
//将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//将image的data加入
[myRequestData appendData:data];
//加入结束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//设置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData];
//http method
[request setHTTPMethod:@"POST"];
}
标签:
原文地址:http://www.cnblogs.com/huaixu/p/5330022.html