Skip to content

Instantly share code, notes, and snippets.

@jstn
Created July 19, 2012 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstn/3140380 to your computer and use it in GitHub Desktop.
Save jstn/3140380 to your computer and use it in GitHub Desktop.
Read an image off disk and iterate through its pixel data byte by byte using Core Graphics
NSString *imagePath = @"/tmp/test.jpg";
CGDataProviderRef imageDataProvider = CGDataProviderCreateWithFilename([imagePath UTF8String]);
CGImageRef image = CGImageCreateWithJPEGDataProvider(imageDataProvider, NULL, false, kCGRenderingIntentDefault);
CGDataProviderRelease(imageDataProvider);
size_t bytesPerPixel = 4;
size_t bitsPerComponent = 8;
size_t imageWidth = CGImageGetWidth(image);
size_t imageHeight = CGImageGetHeight(image);
size_t bytesPerRow = imageWidth * bytesPerPixel;
size_t byteCount = bytesPerRow * imageHeight;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Big | kCGImageAlphaNoneSkipFirst;
CGRect imageRect = CGRectMake(0.0, 0.0, (CGFloat)imageWidth, (CGFloat)imageHeight);
uint8_t *bitmapData = calloc(byteCount, sizeof(uint8_t));
CGContextRef context = CGBitmapContextCreate(bitmapData, imageWidth, imageHeight, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, imageRect, image);
CGImageRelease(image);
CGContextRelease(context);
for (int y = 0; y < imageWidth; y++) {
for (int x = 0; x < imageHeight; x++) {
unsigned long offset = bytesPerPixel * ((imageWidth * y) + x);
uint8_t red = bitmapData[offset + 1];
uint8_t green = bitmapData[offset + 2];
uint8_t blue = bitmapData[offset + 3];
NSLog(@"%d, %d: %d / %d / %d", x, y, red, green, blue);
}
}
free(bitmapData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment