Skip to content

Instantly share code, notes, and snippets.

@catehstn
Created January 19, 2015 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save catehstn/3aef11bc14b8c4dc1710 to your computer and use it in GitHub Desktop.
Save catehstn/3aef11bc14b8c4dc1710 to your computer and use it in GitHub Desktop.
// Turn an image into an array of UIColors.
+ (NSArray *)pixelsForImage:(UIImage *)image {
NSUInteger width = [image size].width;
NSUInteger height = [image size].height;
NSUInteger count = width * height;
NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Add 1 for the alpha channel
size_t numberOfComponents = CGColorSpaceGetNumberOfComponents(colorSpace) + 1;
size_t bitsPerComponent = 8;
size_t bytesPerPixel = (bitsPerComponent * numberOfComponents) / 8;
size_t bytesPerRow = bytesPerPixel * width;
uint8_t *rawData = (uint8_t*)calloc(count * numberOfComponents, sizeof(uint8_t));
CGContextRef context = CGBitmapContextCreate(rawData,
width,
height,
bitsPerComponent,
bytesPerRow,
colorSpace,
(CGBitmapInfo) kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
CGImageRef cgImage = [image CGImage];
CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgImage);
int byteIndex = 0;
for (int i = 0 ; i < count ; ++i) {
CGFloat red = (rawData[byteIndex] * 1.0) / 255.0;
CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
CGFloat blue = (rawData[byteIndex + 2] * 1.0) / 255.0;
CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
byteIndex += 4;
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
[result addObject:color];
}
CGContextRelease(context);
free(rawData);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment