Convert UIImage to NSData without using UIImagePngrepresentation or UIImageJpegRepresentation

H Bastan picture H Bastan · Mar 6, 2013 · Viewed 21.9k times · Source

I Need to convert UIImage to NSData but without using UIImagePngRepresentation or UIImageJpegRepresentation, for images from photolib i can use assetlib method as mentioned here Using ALAssetsLibrary and ALAsset take out Image as NSData , but for captured image , assset url is not there hence in that case i need to convert UIImage directly to bytes with exif data , how can i accomplish this ? please help

Answer

Taz picture Taz · Sep 19, 2013

I had a similar problem, but for security reasons I didn't want to write the data to the default file system as suggested by Wes. I also wanted to be able to add metadata to my image. My solution was as follows:

- (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;
}

To use it, you would do the following:

- (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];

    // ...
}