Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Create an image from an array of colors.
+ (UIImage *)createImageWithPixelData:(NSArray *)pixelData width:(int)width height:(int)height {
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([pixelData count] * numberOfComponents, sizeof(uint8_t));
CGContextRef context = CGBitmapContextCreate(rawData,
width,
height,
bitsPerComponent,
bytesPerRow,
colorSpace,
(CGBitmapInfo) kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
int byteIndex = 0;
for (int index = 0; index < [pixelData count]; index += 1) {
CGFloat r, g, b, a;
BOOL convert = [[pixelData objectAtIndex:index] getRed:&r green:&g blue:&b alpha:&a];
if (!convert) {
// TODO(cate): Handle this.
NSLog(@"Failed, continue");
}
rawData[byteIndex] = r * 255;
rawData[byteIndex + 1] = g * 255;
rawData[byteIndex + 2] = b * 255;
rawData[byteIndex + 3] = a * 255;
byteIndex += 4;
}
CGImageRef imageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:imageRef];
CGContextRelease(context);
CGImageRelease(imageRef);
return newImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.