Created
January 19, 2015 16:23
-
-
Save catehstn/3aef11bc14b8c4dc1710 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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