I've been struggling with this for a couple of hours, and I'm hoping someone else has some insight. I'm looking for a way to get the average RGB color of a 1x1 UIImage. So far I've created a CGImageRef from the UIImage, but I'm really new to CoreGraphics, so I'm not sure where to go from there. Any help is appreciated. Thanks!
Asked
Active
Viewed 1,294 times
1 Answers
1
If you have a CGImage, you get the data by calling
CGDataProviderRef CGImageGetDataProvider (
CGImageRef image
);
Then you can copy the data
CFDataRef CGDataProviderCopyData(
CGDataProviderRef provider
);
Since CFData
is the same as NSData
you can cast it and retrieve the bytes
- (const void *)bytes
Now you have the raw bytes, you can do anything with them, use
CGImageAlphaInfo CGImageGetAlphaInfo (
CGImageRef image
);
CGBitmapInfo CGImageGetBitmapInfo (
CGImageRef image
);
to get information how is the image data stored in the bytes you got.

Jiri
- 2,206
- 1
- 22
- 19
-
Supporting every possible color format of a CGImage (keeping in mind that it may not be the same on any two OS versions or hardware revisions) is an infeasible and undesirable amount of work. Better to just draw the image into a bitmap context you create in a format you choose, and then write the code to inspect the pixels in only one format. – Peter Hosey Oct 02 '11 at 05:36
-
@PeterHosey And while you're at it, you can use the image drawing to calculate the average at the same time, as show in [this](http://stackoverflow.com/questions/12147779/how-do-i-release-a-cgimageref-in-ios/12148136#12148136) answer. – Nikolai Ruhe Aug 28 '12 at 12:02