Skip to content

Instantly share code, notes, and snippets.

@zmorris
Created February 3, 2012 17:22
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 zmorris/1731247 to your computer and use it in GitHub Desktop.
Save zmorris/1731247 to your computer and use it in GitHub Desktop.
LoadImage()
#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