Jakob Halskov
Jakob Halskov

Reputation: 438

Average Color of Mac Screen

I'm trying to find out a way to calculate the average color of the screen using objective-c.

So far I use this code to get a screen shot, which works great:

CGImageRef image1 = CGDisplayCreateImage(kCGDirectMainDisplay);

NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:image1];
// Create an NSImage and add the bitmap rep to it...
NSImage *image = [[NSImage alloc] init];
[image addRepresentation:bitmapRep];

Now my problem is to calculate the average RGB color of this image.

I've found one solution, but the R G and B color components were always calculated to be the same (equal):

NSInteger i = 0;
NSInteger components[3] = {0,0,0};
unsigned char *data = [bitmapRep bitmapData];

NSInteger pixels = ([bitmapRep size].width *[bitmapRep size].height);

do {
    components[0] += *data++;
    components[1] += *data++;
    components[2] += *data++;
} while (++i < pixels);

int red = (CGFloat)components[0] / pixels;
int green = (CGFloat)components[1] / pixels;
int blue = (CGFloat)components[2] / pixels;

Upvotes: 0

Views: 1165

Answers (2)

Heinrich Giesen
Heinrich Giesen

Reputation: 1835

A short analysis of bitmapRep shows that each pixel has 32 bits (4 bytes) where the first byte is unused, it is a padding byte, in other words the format is XRGB and X is not used. (There are no padding bytes at the end of a pixel row).

Another remark: for counting the number of pixels you use the method -(NSSize)size.
You should never do this! size has nothing to do with pixels. It only says how big the image should be depicted (expressed in inch or cm or mm) on the screen or the printer. For counting (or using otherwise) the pixels you should use -(NSInteger)pixelsWide and -(NSInteger)pixelsHigh. But the (wrong) using of -size works if and only if the resolution of the imageRep is 72 dots per inch.

Finally: there is a similar question at Average Color of Mac Screen

Upvotes: 3

Kris Van Bael
Kris Van Bael

Reputation: 2862

Your data is probably aligned as 4 bytes per pixel (and not 3 bytes, like you assume). That would (statistically) explain the near-equal values that you get.

Upvotes: 2

Related Questions