Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImagePickerController Image Type

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?

like image 919
Mick Walker Avatar asked Mar 04 '14 14:03

Mick Walker


1 Answers

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>

like image 181
Dillan Avatar answered Oct 12 '22 13:10

Dillan