Created
April 5, 2015 15:23
-
-
Save 3ign0n/43dd799c33331c3de603 to your computer and use it in GitHub Desktop.
Get pixel data from CGImageRef
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
- (void)testGetPixelDataFromCGImageRefExample { | |
UIImage *image = [self loadImage]; | |
[self rawDataCopyWithImage:image]; | |
[self rawDataDrawWithImage:image]; | |
} | |
- (void)rawDataCopyWithImage:(UIImage*)image | |
{ | |
CGImageRef imageRef = image.CGImage; | |
CGDataProviderRef dataProvider = CGImageGetDataProvider(imageRef); | |
__block CFDataRef dataRef; | |
dataRef = CGDataProviderCopyData(dataProvider); | |
UInt8* buffer = (UInt8*)CFDataGetBytePtr(dataRef); | |
size_t bytesPerRow = CGImageGetBytesPerRow(imageRef); | |
[self printData:buffer width:image.size.width height:image.size.height bytesPerRow:bytesPerRow]; | |
CFRelease(dataRef); | |
} | |
- (void)rawDataDrawWithImage:(UIImage*)image | |
{ | |
CGImageRef imageRef = [image CGImage]; | |
NSUInteger width = CGImageGetWidth(imageRef); | |
NSUInteger height = CGImageGetHeight(imageRef); | |
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); | |
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char)); | |
NSUInteger bytesPerPixel = 4; | |
NSUInteger bytesPerRow = bytesPerPixel * width; | |
NSUInteger bitsPerComponent = 8; | |
CGContextRef context = CGBitmapContextCreate(rawData, width, height, | |
bitsPerComponent, bytesPerRow, colorSpace, | |
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big); | |
CGColorSpaceRelease(colorSpace); | |
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); | |
CGContextRelease(context); | |
[self printData:rawData width:width height:height bytesPerRow:bytesPerRow]; | |
free(rawData); | |
} | |
- (void)printData:(UInt8*)data width:(NSInteger)width height:(NSInteger)height bytesPerRow:(size_t)bytesPerRow | |
{ | |
for (NSInteger x=0; x<width; x++) | |
{ | |
for (NSInteger y=0; y<height; y++) | |
{ | |
// ピクセルのポインタを取得する | |
UInt8* pixelPtr = data + (int)(y) * bytesPerRow + (int)(x) * 4; | |
// 色情報を取得する | |
UInt8 r = *(pixelPtr + 2); // 赤 | |
UInt8 g = *(pixelPtr + 1); // 緑 | |
UInt8 b = *(pixelPtr + 0); // 青 | |
NSLog(@"x:%ld y:%ld R:%d G:%d B:%d", (long)x, (long)y, r, g, b); | |
} | |
} | |
} | |
- (UIImage*)loadImage | |
{ | |
return [UIImage imageNamed:@"colorpattern.jpg"]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment