Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 871
Jared Egan Avatar asked Oct 31 '11 01:10

Jared Egan


3 Answers

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

For a working example click here.

Thank you.

like image 102
damithH Avatar answered Oct 27 '22 23:10

damithH


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;
like image 43
Jared Egan Avatar answered Oct 27 '22 22:10

Jared Egan


you can use this

NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

and simply cast imageData to CFDataRef

CFDataRef = (CFDataRef) imageData;
like image 30
Shahrukh A. Avatar answered Oct 27 '22 22:10

Shahrukh A.