UIImagePickerController图像类型

时间:2014-03-04 14:08:06

标签: ios7 uiimage uiimagepickercontroller

我的应用程序允许用户从设备相机胶卷中选择图像。我想验证所选图像的格式是PNG还是JPG图像。

是否可以在- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info委托方法中执行此操作?

1 个答案:

答案 0 :(得分:8)

是的,您可以在委托回调中执行此操作。您可能已经注意到UIImagePickerControllerMediaType信息字典键将返回“public.image”字符串作为UTI,这不足以满足您的需要。但是,这可以通过使用与信息字典中的UIImagePickerControllerReferenceURL键关联的URL来完成。例如,实现可能类似于下面的方法。

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    NSURL *assetURL = info[UIImagePickerControllerReferenceURL];

    NSString *extension = [assetURL pathExtension];
    CFStringRef imageUTI = (UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,(__bridge CFStringRef)extension , NULL));

    if (UTTypeConformsTo(imageUTI, kUTTypeJPEG))
    {
        // Handle JPG
    }
    else if (UTTypeConformsTo(imageUTI, kUTTypePNG))
    {
        // Handle PNG
    }
    else
    {
        NSLog(@"Unhandled Image UTI: %@", imageUTI);
    }

    CFRelease(imageUTI);

    [self.imageView setImage:image];

    [picker dismissViewControllerAnimated:YES completion:NULL];
}

您还需要链接MobileCoreServices.framework并添加#import <MobileCoreServices/MobileCoreServices.h>