I wanted to convert a directory of Windows bitmaps to PNG images today. I must be missing something in Graphic Converter. (I can get to the batch window, but how do I make it convert?) After a few minutes, I decided just to write something for the command line. Apple's image source/destination abstractions make it easy. My program is less than forty lines:
/* Compile with:
gcc -o imageToPNG imageToPNG.m -framework Foundation -framework Carbon
*/
#import <Foundation/Foundation.h>
#import <stdio.h>
int main( int argc, char *argv[] ) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int i;
for (i = 1; i < argc; i++) {
NSString *spath = [NSString stringWithUTF8String: argv[i]];
CGImageSourceRef sref = CGImageSourceCreateWithURL( (CFURLRef) [NSURL fileURLWithPath: spath], NULL );
if (sref == NULL) {
fprintf( stderr, "Could not create image source for file %s\n", argv[i] );
continue;
}
NSString *dpath = [[[spath stringByExpandingTildeInPath]
stringByDeletingPathExtension]
stringByAppendingPathExtension: @"png"];
CGImageDestinationRef dref = CGImageDestinationCreateWithURL(
(CFURLRef)[NSURL fileURLWithPath: dpath],
(CFStringRef) @"public.png",
1, NULL );
if (dref == NULL) {
fprintf( stderr, "Could not create image destination for file %s\n", argv[i] );
} else {
CGImageDestinationAddImageFromSource( dref, sref, 0, NULL );
if (!CGImageDestinationFinalize(dref)) {
fprintf( stderr, "Error converting %s to %s\n", argv[i], [dpath UTF8String] );
}
CFRelease(dref);
}
CFRelease(sref);
}
[pool release];
return 0;
}