My application allows a user to select an image from the devices camera roll. I would like to validate that the format of the selected image is either a PNG or JPG image.
is it possible to do this in the - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
delegate method?
Yes, you can do this in the delegate callback. As you may have noticed the UIImagePickerControllerMediaType
info dictionary key will return a "public.image" string back as the UTI, which isn't sufficient for your purpose. However, this can be done by using the url associated with the UIImagePickerControllerReferenceURL
key in the info dictionary. For example, the implementation might look similar to the method below.
- (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];
}
You'll also need to link against MobileCoreServices.framework and add a #import <MobileCoreServices/MobileCoreServices.h>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With