1. 程式人生 > >如何從UIImage或者CGImage獲取到圖片的畫素資料

如何從UIImage或者CGImage獲取到圖片的畫素資料

CFDataRefCopyImagePixels(CGImageRef inImage){returnCGDataProviderCopyData(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));constunsignedchar* buffer =CFDataGetBytePtr(data);
CFDataRef bitmapData = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));

這裡拿到的bitmapData變數裡面就包含了所有畫素的所有資訊,記得用完了之後要釋放bitmapData所佔有的空間。CFData的用法可以參考官方文件

使用CFDataGetLength函式可以看到,這個資料的長度是4*image.size.width*image.size.height。也就是每一個畫素點都佔據了四個位元組的長度,依次序分別是RGBA,即紅色、綠色、藍色值和透明度值。

使用函式CFDataGetBytePtr(bitmapData) 就可以拿到位元組陣列的指標了。