2011-01-23 29 views
7

我正在開發一個OS X應用程序,並希望使用ImageMagick來執行一些圖像操作。我注意到CLI ImageMagick實用程序需要一些環境變量才能工作。是否可以將ImageMagick工具套件與我的應用程序捆綁在一起並在我的代碼中使用它們?捆綁帶OS X App的ImageMagick庫?

回答

10

因此,這裏是我的解決方案:

我捆綁OS X binary釋放我的項目,並使用NSTask調用二進制文件。您需要爲NSTask指定「MAGICK_HOME」和「DYLD_LIBRARY_PATH」環境變量才能正常工作。這是我正在使用的片段。

請注意,此示例被硬編碼爲使用「複合」命令...並使用硬編碼參數,但您可以將其更改爲任何您喜歡的內容......它僅用作概念證明。

-(id)init 
{ 
    if ([super init]) 
    { 
     NSString* bundlePath = [[NSBundle mainBundle] bundlePath]; 
     NSString* imageMagickPath = [bundlePath stringByAppendingPathComponent:@"/Contents/Resources/ImageMagick"]; 
     NSString* imageMagickLibraryPath = [imageMagickPath stringByAppendingPathComponent:@"/lib"]; 

     MAGICK_HOME = imageMagickPath; 
     DYLD_LIBRARY_PATH = imageMagickLibraryPath; 
    } 
    return self; 
} 

-(void)composite 
{ 
    NSTask *task = [[NSTask alloc] init]; 

    // the ImageMagick library needs these two environment variables. 
    NSMutableDictionary* environment = [[NSMutableDictionary alloc] init]; 
    [environment setValue:MAGICK_HOME forKey:@"MAGICK_HOME"]; 
    [environment setValue:DYLD_LIBRARY_PATH forKey:@"DYLD_LIBRARY_PATH"]; 

    // helper function from 
    // http://www.karelia.com/cocoa_legacy/Foundation_Categories/NSFileManager__Get_.m 
    NSString* pwd = [Helpers pathFromUserLibraryPath:@"MyApp"]; 

    // executable binary path 
    NSString* exe = [MAGICK_HOME stringByAppendingPathComponent:@"/bin/composite"]; 

    [task setEnvironment:environment]; 
    [task setCurrentDirectoryPath:pwd]; // pwd 
    [task setLaunchPath:exe]; // the path to composite binary 
    // these are just example arguments 
    [task setArguments:[NSArray arrayWithObjects: @"-gravity", @"center", @"stupid hat.png", @"IDR663.gif", @"bla.png", nil]]; 
    [task launch]; 
    [task waitUntilExit]; 
} 

該解決方案捆綁散裝整個庫與您的版本(目前37MB),所以它可能是不太理想的一些解決方案,但它工作:-)

2

可能嗎?是。許多應用程序都這樣做了,但可能很乏味。

NSTask允許自定義環境變量。

+0

我要找做同樣的事情。任何幫助都是好的AFAIK ImageMagick只支持絕對路徑,所以你不能在路徑中使用例如tilds。因此,雖然NSTask可以工作,但我只是將蘋果公司的ImageMagick庫放在任何安裝應用程序的高清「/」區域。有APIs MagickWand MagickCore PerlMagick Magick ++,但我還沒有找到蘋果呢! – markhunte 2011-01-23 19:35:40

相關問題