Christina Christina - 1 year ago 211
Objective-C Question

convert UIImage to NSData

I am using this code in my app which will help me to send a image.

However, I have an image view with an image. I have no file in appbundle but have the image in my side. How can I change the below code ? Can anyone tell me how can I convert


// Attach an image to the email
NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"jpg"];
NSData *myData = [NSData dataWithContentsOfFile:path];
[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];

Answer Source

Try one of the following, depending on your image format:


Returns the data for the specified image in JPEG format.

NSData * UIImageJPEGRepresentation (
   UIImage *image,
   CGFloat compressionQuality


Returns the data for the specified image in PNG format

NSData * UIImagePNGRepresentation (
   UIImage *image

Here the docs.


if you want to access the raw bytes that make up the UIImage, you could use this approach:

CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
const uint8_t* bytes = [data bytes];

This will give you the low-level representation of the image RGB pixels. (Omit the CFBridgingRelease bit if you are not using ARC).