IOS调用相机和相册

使用UIImagePickerController调用系统相机和相册,调用相机时先判断相机是否可用:

//相机
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"系统相机不可用!" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
            [alertView show];
            [alertView release];
            alertView = nil;
            return;
        }
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
        [imagePicker release];

如果要调用相册,很简单,只要把sourceType改成UIImagePickerControllerSourceTypePhotoLibrary即可。

需要实现协议UIImagePickerControllerDelegate,拍完照或者选择了某张照片后,会调用这个协议里的方法:

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

具体的处理代码:

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [UIApplication sharedApplication].statusBarHidden = NO;
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    NSData *data;
    if ([mediaType isEqualToString:@"public.image"]){
        UIImage *originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
        if (UIImagePNGRepresentation(originImage) == nil) {
            data = UIImageJPEGRepresentation(originImage, 1);
        } else {
            data = UIImagePNGRepresentation(originImage);
        }
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        _imageView.image = [UIImage imageWithData:data];
    }
}

执行后,_imageView里就包含了这张图片。

 

posted @ 2013-08-22 10:17  秃鹰  阅读(342)  评论(0)    收藏  举报