Created
February 3, 2012 17:22
-
-
Save zmorris/1731247 to your computer and use it in GitHub Desktop.
LoadImage()
This file contains 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
#include "CoreGraphics/CGDataProvider.h" | |
#include "CoreGraphics/CGImage.h" | |
#include "CoreGraphics/CGBitmapContext.h" | |
void* LoadImage( const char *path, int *width, int *height ) | |
{ | |
CGDataProviderRef dataProvider = CGDataProviderCreateWithFilename( path ); | |
UInt8 *pixels = nil; | |
if( dataProvider ) | |
{ | |
CGImageRef image = CGImageCreateWithPNGDataProvider( dataProvider, NULL, false, kCGRenderingIntentDefault ); | |
if( !image ) image = CGImageCreateWithJPEGDataProvider( dataProvider, NULL, false, kCGRenderingIntentDefault ); | |
if( image ) | |
{ | |
/*// this doesn't work because of a bug in CGImageRef that renders a PNG image incorrectly so that zero alpha pixels turn out white | |
CFDataRef data = CGDataProviderCopyData( CGImageGetDataProvider( image ) ); | |
if( data ) | |
{ | |
int length = CFDataGetLength( data ); | |
pixels = (UInt8*) malloc( length ); | |
if( pixels ) | |
{ | |
CFDataGetBytes( data, CFRangeMake( 0, length ), pixels ); | |
*width = CGImageGetWidth( image ); | |
*height = CGImageGetHeight( image ); | |
} | |
CFRelease( data ); | |
}*/ | |
// draw the image transparently onto a CGBitmapContext | |
*width = CGImageGetWidth( image ); | |
*height = CGImageGetHeight( image ); | |
pixels = (UInt8*) malloc( (*width)*(*height)*4 ); | |
if( pixels ) | |
{ | |
CGContextRef context = CGBitmapContextCreate( pixels, *width, *height, 8, *width*4, CGImageGetColorSpace( image ), kCGImageAlphaPremultipliedLast ); | |
if( context ) | |
{ | |
CGContextClearRect( context, CGRectMake( 0, 0, *width, *height ) ); | |
CGContextDrawImage( context, CGRectMake( 0, 0, *width, *height ), image ); // now pixels contains image pixels | |
CGContextRelease( context ); | |
} | |
else | |
{ | |
free( pixels ); | |
pixels = nil; | |
} | |
} | |
CFRelease( image ); | |
} | |
CFRelease( dataProvider ); | |
} | |
return( pixels ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment