Created
June 19, 2011 11:47
-
-
Save chrishulbert/1034150 to your computer and use it in GitHub Desktop.
Image manipulation in obj-c / iphone
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
typedef unsigned char byte; | |
#define Clamp255(a) (a>255 ? 255 : a) | |
+ (UIImage*) fromImage:(UIImage*)source toColourR:(int)colR g:(int)colG b:(int)colB { | |
// Thanks: http://brandontreb.com/image-manipulation-retrieving-and-updating-pixel-values-for-a-uiimage/ | |
CGContextRef ctx; | |
CGImageRef imageRef = [source CGImage]; | |
NSUInteger width = CGImageGetWidth(imageRef); | |
NSUInteger height = CGImageGetHeight(imageRef); | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); | |
byte *rawData = malloc(height * width * 4); | |
NSUInteger bytesPerPixel = 4; | |
NSUInteger bytesPerRow = bytesPerPixel * width; | |
NSUInteger bitsPerComponent = 8; | |
CGContextRef context = CGBitmapContextCreate(rawData, width, height, | |
bitsPerComponent, bytesPerRow, colorSpace, | |
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); | |
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); | |
CGContextRelease(context); | |
int byteIndex = 0; | |
for (int ii = 0 ; ii < width * height ; ++ii) | |
{ | |
int grey = (rawData[byteIndex] + rawData[byteIndex+1] + rawData[byteIndex+2]) / 3; | |
rawData[byteIndex] = Clamp255(colR*grey/256); | |
rawData[byteIndex+1] = Clamp255(colG*grey/256); | |
rawData[byteIndex+2] = Clamp255(colB*grey/256); | |
byteIndex += 4; | |
} | |
ctx = CGBitmapContextCreate(rawData, | |
CGImageGetWidth( imageRef ), | |
CGImageGetHeight( imageRef ), | |
8, | |
bytesPerRow, | |
colorSpace, | |
kCGImageAlphaPremultipliedLast ); | |
CGColorSpaceRelease(colorSpace); | |
imageRef = CGBitmapContextCreateImage (ctx); | |
UIImage* rawImage = [UIImage imageWithCGImage:imageRef]; | |
CGImageRelease(imageRef); | |
CGContextRelease(ctx); | |
free(rawData); | |
return rawImage; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment