convert UIImage to NSData
Solution 1:
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).
Solution 2:
NSData *imageData = UIImagePNGRepresentation(myImage.image);
Solution 3:
If you have an image inside a UIImageView , e.g. "myImageView", you can do the following:
Convert your image using UIImageJPEGRepresentation() or UIImagePNGRepresentation() like this:
NSData *data = UIImagePNGRepresentation(myImageView.image);
//or
NSData *data = UIImageJPEGRepresentation(myImageView.image, 0.8);
//The float param (0.8 in this example) is the compression quality
//expressed as a value from 0.0 to 1.0, where 1.0 represents
//the least compression (or best quality).
You can also put this code inside a GCD block and execute in another thread, showing an UIActivityIndicatorView during the process ...
//*code to show a loading view here*
dispatch_queue_t myQueue = dispatch_queue_create("com.my.queue", DISPATCH_QUEUE_SERIAL);
dispatch_async(myQueue, ^{
NSData *data = UIImagePNGRepresentation(myImageView.image);
//some code....
dispatch_async( dispatch_get_main_queue(), ^{
//*code to hide the loading view here*
});
});
Solution 4:
Create the reference of image....
UIImage *rainyImage = [UIImage imageNamed:@"rainy.jpg"];
displaying image in image view... imagedisplay is reference of imageview:
imagedisplay.image = rainyImage;
convert it into NSData
by passing UIImage
reference and provide compression quality in float values:
NSData *imgData = UIImageJPEGRepresentation(rainyImage, 0.9);