2015-07-26

JSTalk script for Acorn, crunching images for iOS

So it was time to crunch images for inclusion in an iOS app again. Because I ditched GIMP and moved to Acorn, I can't reuse my old Scheme script.

I had to use JSTalk instead. It is by the same dude that wrote Acorn. It is basically a JavaScript wrapper to Core Foundation.

I decided on JSTalk over AppleScript after glancing at the AppleScript syntax for about 5 seconds. I heard about JSTalk from the Acorn scripting docs.

Anyway, I had finished editing my "@2" images manually, and I needed the half-size image files. I had them all in one directory.

I ran this script straight from the JSTalk Editor.

var acorn = JSTalk.application("Acorn");
var dirPath = @"/Users/jeff/VGT/art/vegetable photos/Working Temp/";
var fileManager = [[NSFileManager alloc] init];
var dirEnum = [fileManager enumeratorAtPath:dirPath];
var fileName = [dirEnum nextObject];

while (fileName) {
    NSLog(fileName);
    
    var range = [fileName rangeOfString:@"@2.jpg"];
    if (range.location == NSNotFound) {
        continue;
    }
    
    var fullPathFileName = dirPath + fileName;
    NSLog(fullPathFileName);
    
    var doc = acorn.open_(fullPathFileName);
    var size = doc.canvasSize()
    var newWidth = size.width / 2;
    doc.scaleImageToWidth(newWidth);
    
    var endIndex = [fileName length] - 6;
    // How do I stringify this number so I can pass it to NSLog?
    // NSLog(endIndex);
    
    var modFileName = [fileName substringToIndex:endIndex];
    NSLog(modFileName);
    var modFullPathFileName = dirPath + modFileName + ".jpg";
    NSLog(modFullPathFileName);
    
    doc.dataRepresentationOfType("public.png").writeToFile(modFullPathFileName);
    doc.close();
    fileName = [dirEnum nextObject];
}

Some problems I encountered:
  • I could only pass 1 parameter to NSLog. The string format specifiers (%s and %@) just got lost.
  • I could not do while ((fileName = [dirEnum nextObject])). It just couldn't understand that.
  • The class method [NSFileManaged defaultManager] did not work, so I had to init my own. I'm not sure if that is a JSTalk problem or because I've never written an OS X app before and that is normal.
Ug! A buddy just showed me the JavaScript for Automation video from WWCD 2014. I'm so far behind the tech curve, as usual.

No comments:

Post a Comment