How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?
CFDataRef CopyImagePixels(CGImageRef inImage)
{
return CGDataProviderCopyData(CGImageGetDataProvider(inImage));
}
CFDataGetBytePtr
to get to the actual bytes (and various CGImageGet*
NSString * path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"jpg"];
UIImage * img = [[UIImage alloc]initWithContentsOfFile:path];
CGImageRef image = [img CGImage];
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(image));
const unsigned char * buffer = CFDataGetBytePtr(data);
CFDataRef bitmapData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
这里拿到的bitmapData变量里面就包含了所有像素的所有信息,记得用完了之后要释放bitmapData所占有的空间。CFData的用法可以参考官方文档。
使用CFDataGetLength函数可以看到,这个数据的长度是4*image.size.width*image.size.height。也就是每一个像素点都占据了四个字节的长度,依次序分别是RGBA,即红色、绿色、蓝色值和透明度值。
使用函数CFDataGetBytePtr(bitmapData) 就可以拿到字节数组的指针了。