2014-03-04 123 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>

相關問題