iPhone调用相机或者打开相册获取图片

iPhone调用相机或者打开相册获取图片本篇文章主要讲解了在iPhone中如何调用相机或者打开相册获取图片,并可以设置压缩比。通过本文,你将了解到如何使用UIImagePickerController获取图片,并进行裁剪处理。一、UIImagePickerController简介UIImagePickerController是iOS中的一个组件,它允许用户从摄像头或图片库中选择图片。它可以作为一个模态视图控制器(Modal View Controller)呈现给用户,从而获取图片。二、使用UIImagePickerController获取图片要使用UIImagePickerController获取图片,首先需要创建一个UIImagePickerController实例,并设置其sourceType属性为UIImagePickerControllerSourceTypeCamera或UIImagePickerControllerSourceTypePhotoLibrary,分别表示从摄像头或图片库中获取图片。在我们的示例代码中,我们使用了UIActionSheet来让用户选择是从摄像头还是图片库中获取图片。当用户选择后,我们使用switch语句来判断用户的选择,并执行相应的操作。 //从相机获取case 0: { if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init]; imagePickController.sourceType = UIImagePickerControllerSourceTypeCamera; imagePickController.allowsEditing = YES; imagePickController.delegate = self; [mCurrentController presentViewController:imagePickController animated:YES completion:^{}]; } else { UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提醒" message:@"此设备无摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil]; [alertView show]; } break; //从相册获取case 1: { if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) { UIImagePickerController *imagePickController = [[UIImagePickerController alloc]init]; imagePickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; imagePickController.allowsEditing = YES; imagePickController.delegate = self; [mCurrentController presentViewController:imagePickController animated:YES completion:^{}]; } break; }三、设置图片压缩比在获取图片后,我们可以使用UIImagePickerController的editingInfo属性来设置图片的压缩比。editingInfo属性是一个字典,其中包含了图片的meta信息和图片数据。 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; NSData *imageData = UIImageJPEGRepresentation(image, 0.5); //设置压缩比为0.5 // ... }四、小结本文讲解了如何使用UIImagePickerController获取图片,并设置图片的压缩比。通过本文,你可以了解到UIImagePickerController的使用方法,并在自己的应用程序中实现图片获取和裁剪功能。
docx 文件大小:62.08KB