我的应用程序允许用户从设备相机胶卷中选择图像。我想验证所选图像的格式是 PNG 还是 JPG 图像。
是否可以在- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
委托方法中执行此操作?
是的,您可以在委托回调中执行此操作。您可能已经注意到,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>