UIActionSheet* actionSheet = [[UIActionSheet alloc]
initWithTitle:nil
delegate:self
cancelButtonTitle:@”取消”
destructiveButtonTitle:nil
otherButtonTitles:@”拍照”,@”从相册选取”,nil];
[actionSheet showInView:self.view];
pragma mark—-
pragma mark—- ActionSheet Delegate Methods
-
(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
switch (buttonIndex) {
case 0://拍照
{
if (![self ifCanUseSystemCamera]) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@”此应用已被禁用系统相机” message:@”请在iPhone的 \”设置->隐私->相机\” 选项中,允许 \”自己App的名字\” 访问你的相机” delegate:self cancelButtonTitle:nil otherButtonTitles:@”确认”, nil];
[alert show];
}else {
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 -
pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController )picker didFinishPickingMediaWithInfo:(NSDictionary )info {
if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeImage]) {
UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
[self performSelector:@selector(saveImage:) withObject:img afterDelay:0.5];
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
//点击cancel时调用该方法 - (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 *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@”image.jpg”];
success = [fileManager fileExistsAtPath:imageFilePath];
if(success) {
success = [fileManager removeItemAtPath:imageFilePath error:&error];
}
//UIImage *smallImage2=[self scaleFromImage:image toSize:CGSizeMake(80.0f, 80.0f)];//将图片尺寸改为80*80
UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(93, 93)];
[UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
//UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
NSData *imageData = UIImageJPEGRepresentation(smallImage, 1.0);
[self userSetAvatarWithData:imageData];
}
//上传至服务器 -
(void)userSetAvatarWithData:(NSData *)imageData {
AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
manger.responseSerializer = [AFHTTPResponseSerializer serializer];
manger.requestSerializer = [AFHTTPRequestSerializer serializer];
manger.requestSerializer.timeoutInterval = 10;NSString *url = [NSString stringWithFormat:@”上传头像的接口”];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[manger POST:url parameters:nil constructingBodyWithBlock:^(id formData) {
[formData appendPartWithFileData:data name:@”随便取不能为空” fileName:@”随便取不能为空” mimeType:@”image/jpg”];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@”上传成功”);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@”上传失败”);
}];
}
// 此方法可以改变图片的大小,方便上传到服务器
- (UIImage ) scaleFromImage: (UIImage ) image toSize: (CGSize) size {
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
//2.保持图片原来的长宽比,生成一个缩略图
- (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;
}
//判断是否支持相机
- (BOOL)ifCanUseSystemCamera{
NSString *mediaType = AVMediaTypeVideo;
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
NSLog(@"相机权限受限");
return NO;
}
return YES;
}