Created
July 6, 2015 16:39
-
-
Save kkaefer/fd114fdbbe1a3a17a891 to your computer and use it in GitHub Desktop.
Reading images
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
// Compile with: | |
// clang++ read_png.mm -framework ImageIO -framework CoreGraphics -framework CoreServices | |
#import <ImageIO/ImageIO.h> | |
int main() { | |
const unsigned char png[] = { | |
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, | |
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, | |
0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, | |
0x0D, 0x49, 0x44, 0x41, 0x54, 0x08, 0x1D, 0x63, 0x10, 0xDF, 0xFE, 0x37, | |
0x0F, 0x00, 0x04, 0xEE, 0x02, 0x3A, 0x01, 0x32, 0x70, 0x00, 0x00, 0x00, | |
0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}; | |
const size_t length = sizeof(png); | |
CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, png, length, | |
kCFAllocatorNull); | |
if (!data) { | |
fprintf(stderr, "could not create CFDataRef\n"); | |
return 1; | |
} | |
CGImageSourceRef image_source = CGImageSourceCreateWithData(data, NULL); | |
if (!image_source) { | |
CFRelease(data); | |
fprintf(stderr, "could not create CGImageSourceRef\n"); | |
return 1; | |
} | |
CGImageRef image = CGImageSourceCreateImageAtIndex(image_source, 0, NULL); | |
if (!image) { | |
CFRelease(image_source); | |
CFRelease(data); | |
fprintf(stderr, "could not create CGImageRef\n"); | |
return 1; | |
} | |
CGColorSpaceRef color_space = CGColorSpaceCreateDeviceRGB(); | |
if (!color_space) { | |
CGImageRelease(image); | |
CFRelease(image_source); | |
CFRelease(data); | |
fprintf(stderr, "could not create CGColorSpaceRef\n"); | |
return 1; | |
} | |
assert(CGImageGetWidth(image) == 1); | |
assert(CGImageGetHeight(image) == 1); | |
CGRect rect = {{0, 0}, {1, 1}}; | |
char img[4]; | |
CGContextRef context = CGBitmapContextCreate(img, 1, 1, 8, 1 * 4, color_space, | |
kCGImageAlphaPremultipliedLast); | |
if (!context) { | |
CGColorSpaceRelease(color_space); | |
CGImageRelease(image); | |
CFRelease(image_source); | |
CFRelease(data); | |
fprintf(stderr, "could not create CGBitmapContext\n"); | |
return 1; | |
} | |
CGContextSetBlendMode(context, kCGBlendModeCopy); | |
CGContextDrawImage(context, rect, image); | |
CGContextRelease(context); | |
CGColorSpaceRelease(color_space); | |
CGImageRelease(image); | |
CFRelease(image_source); | |
CFRelease(data); | |
fprintf(stderr, "expected r:% 4d g:% 4d b:% 4d a:% 4d\n", 23, 183, 252, 110); | |
fprintf(stderr, " actual r:% 4d g:% 4d b:% 4d a:% 4d\n", img[0], img[1], img[2], img[3]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment