如何从UIImage或者CGImage获取到图片的像素数据

来源:互联网 发布:java大量数据处理调优 编辑:程序博客网 时间:2024/06/05 19:09

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

CFDataRef CopyImagePixels(CGImageRef inImage){    return CGDataProviderCopyData(CGImageGetDataProvider(inImage));}

Use CFDataGetBytePtr to get to the actual bytes (and various CGImageGet* methods to understand how to interpret them).

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) 就可以拿到字节数组的指针了。


0 0
原创粉丝点击