Skip to content

Instantly share code, notes, and snippets.

@catehstn
Created January 19, 2015 16:24
Show Gist options
  • Save catehstn/2695a2ced023658fc9bd to your computer and use it in GitHub Desktop.
Save catehstn/2695a2ced023658fc9bd to your computer and use it in GitHub Desktop.
// 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