Search code examples
objective-ciosipadcocoa-touchnsdata

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 myimage to NSData ?

// 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"];

Solution

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

    UIImageJPEGRepresentation

    Returns the data for the specified image in JPEG format.

    NSData * UIImageJPEGRepresentation (
       UIImage *image,
       CGFloat compressionQuality
    );
    

    UIImagePNGRepresentation

    Returns the data for the specified image in PNG format

    NSData * UIImagePNGRepresentation (
       UIImage *image
    );
    

    Here the docs.

    EDIT:

    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).