2014-03-04 126 views
5

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

是否有可能在- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info委托方法中做到这一点?

回答

8

是的,你可以在委托回调中做到这一点。正如你可能已经注意到,UIImagePickerControllerMediaType信息字典键将返回一个“public.image”字符串作为UTI,这不足以满足你的目的。但是,可以使用info字典中与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>

相关问题