How to save image data with exif information from UIImagePickerController

By | 2013 年 10 月 5 日

The UIImage returned from UIImagePickerController is without exif information, if we want generate an NSData from it, saving to disk or sharing via network for example. We can mix the exif information into the NSData.

Like this:

- (NSData *)dataFromImage:(UIImage *)image metadata:(NSDictionary *)metadata mimetype:(NSString *)mimetype
{
    NSMutableData *imageData = [NSMutableData data];
    CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, (__bridge CFStringRef)mimetype, NULL);
    CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, uti, 1, NULL);

    if (imageDestination == NULL)
    {
        NSLog(@"Failed to create image destination");
        imageData = nil;
    }
    else
    {
        CGImageDestinationAddImage(imageDestination, image.CGImage, (__bridge CFDictionaryRef)metadata);

        if (CGImageDestinationFinalize(imageDestination) == NO)
        {
            NSLog(@"Failed to finalise");
            imageData = nil;
        }
        CFRelease(imageDestination);
    }

    CFRelease(uti);

    return imageData;
}

and in the callback of UIImagePickerController, do this:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSDictionary *metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
    NSString *mimeType = @"image/jpeg"; // ideally this would be dynamically set. Not defaulted to a jpeg!

    // you could add to the metadata dictionary (after converting it to a mutable copy) if you needed to.

    // convert to NSData
    NSData *imageData = [self dataFromImage:image metadata:metadata mimetype:mimeType];

    // ...
}

Referrence
http://stackoverflow.com/questions/15239719/convert-uiimage-to-nsdata-without-using-uiimagepngrepresentation-or-uiimagejpegr

3 thoughts on “How to save image data with exif information from UIImagePickerController

  1. 波波

    大神,我想问一下,我也是用CGImageDestinationRef去设置图片的exif和tiff信息的,但是为什么我保存不进去呢,我是先把原图压缩,再保存的。

    Reply

波波进行回复 取消回复

电子邮件地址不会被公开。 必填项已用*标注