今天研究UIImagePickerControlle这个类,用它来打开摄像头和本地照片库。找到一个好的办法也是比較简单的方法来将选择好的图片显示我们想要的UIImageView上。以下通过代码来具体解说.
这是我的ActionSheet 协议事件
#pragma mark - ActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
photoPicker = [[PhotoPickerControlleralloc]initWithDelegate:self];
photoPicker.useCameraName = actionSheet.title;
if(buttonIndex == 0)
{
/*选择已有照片*/
[selfLocalPhoto];
}
else if(buttonIndex ==1)
{
/*拍照从相机获取*/
[selftakePhoto];
}
}
图片:
当点击第一项时调用:
#pragma mark - 本地照片库
-(void)LocalPhoto
{
UIImagePickerController *picker = [[UIImagePickerControlleralloc]init];
picker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary; //类型
picker.delegate =self; //协议
picker.allowsEditing =YES;
[selfpresentViewController:picker animated:YEScompletion:nil];
}
当点击第二项时调用:
#pragma mark - 从相机获取
-(void)takePhoto
{
if ([UIImagePickerControllerisSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController *picker = [[UIImagePickerControlleralloc] init];
picker.delegate =self;
picker.allowsEditing =YES;
picker.sourceType =UIImagePickerControllerSourceTypeCamera;
[selfpresentViewController:picker animated:YEScompletion:nil];
}
else
{
UIAlertView *alerView = [[UIAlertViewalloc]initWithTitle:@"无法拍照" message:@"此设备拍照功能不可用" delegate:selfcancelButtonTitle:@"确定"otherButtonTitles:nil];
[alerViewshow];
}
}
以下是你选择照片调用的协议方法:
#pragma mark - UIImagePickerCont≥rollerDelegate
/*当选择一张图片后进入*/
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *type = [infoobjectForKey:UIImagePickerControllerMediaType]; //得到类型
if([typeisEqualToString:(NSString *)kUTTypeImage])
{
UIImage *image = [infoobjectForKey:UIImagePickerControllerEditedImage]; //得到相机图片
if (!image)
{
image = [info objectForKey:UIImagePickerControllerOriginalImage];
}
[selfperformSelector:@selector(uploadUserHeadPicture:)withObject:image afterDelay:0.01];
[picker dismissViewControllerAnimated:YEScompletion:nil];
}
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
[picker dismissViewControllerAnimated:YEScompletion:nil];
}
/*上传图片*/
- (void)uploadUserHeadPicture:(UIImage *)image
{
NSArray *dirPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString * docsDir = [dirPaths objectAtIndex:0]; //得到documen文件夹下
NSData *imageData = UIImagePNGRepresentation(image); //将图片转化为png
databasePath = [NSStringstringWithFormat:@"%@/%@",docsDir,HeadImgName];//图片文件完整的路径
[imageDatawriteToFile:databasePathatomically:YES];//将图片写入到文件里去
UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"上传成功" delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:nil,nil];
[alertshow];
[self.mTableViewreloadData];
}
//此时主要代码已经完毕假设你要显示你选择的图片仅仅需通过[UIImageimageWithContentsOfFile:databasePath];载入就是了。
HeadImgName 是个宏定义
#define HeadImgName @"head.png"
做完这些后能够通过iFunBox软件查看你的应用程序document文件夹以下是否保存有你刚刚上传的图片。
当然往往项目里面还是会把它保存到server中去。