Jared Egan
Jared Egan

Reputation: 1278

How do I convert a UIImage to NSData or CFDataRef?

How do I convert a UIImage to NSData or CFDataRef? I need to pass a CFDataRef to ABPersonSetImageData.

Upvotes: 11

Views: 16482

Answers (4)

Olcay Ertaş
Olcay Ertaş

Reputation: 6228

For those who wondering what is difference between NSData and CFData, here is the explanation from Apple Docs:

CFData is “toll-free bridged” with its Cocoa Foundation counterpart, NSData. What this means is that the Core Foundation type is interchangeable in function or method calls with the bridged Foundation object. In other words, in a method where you see an NSData * parameter, you can pass in a CFDataRef, and in a function where you see a CFDataRef parameter, you can pass in an NSData instance. This also applies to concrete subclasses of NSData. See Toll-Free Bridged Types for more information on toll-free bridging.

This explains why casting NSData to CFData works.

Upvotes: 0

damithH
damithH

Reputation: 5178

CFDataRef cfdata = CFDataCreate(NULL, [imageData bytes], [imageData length]);

For a working example click here.

Thank you.

Upvotes: 3

Shahrukh A.
Shahrukh A.

Reputation: 1101

you can use this

NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

and simply cast imageData to CFDataRef

CFDataRef = (CFDataRef) imageData;

Upvotes: 7

Jared Egan
Jared Egan

Reputation: 1278

This worked for me, for a PNG image. For other image types, I assume you just have to find the corresponding UIImage...Representation method.

UIImage *image = [UIImage imageNamed:@"imageName.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];

If you need a CFDataRef for a UIImage, it's just one more line.

CFDataRef imgDataRef = (CFDataRef)imageData;

Upvotes: 22

Related Questions