Search code examples
applescriptjavascript-automation

save contact's profile picture using JavaScript for Automation


I would like to write the profile picture of a contact to a file.

1) how to read TIFF image?

The dictionary describes the image property: image (*TIFFPicture* or missing value) : Image for person.

In the dictionary TIFFPicture is a link, but when I click it there's no additional information. When reading it the value seems to be <>. How do I read it as an image?

2) how to write TIFF image?

When writing it to a file, what format should be specified? The dictionary says: [as: type class] : how to write the data: as text, data, list, etc.

In case as: is needed for writing an image, what type should be specified? When I use e.g. as: 'data' the error is "Can't convert types".

Example:

var app = Application.currentApplication();
app.includeStandardAdditions = true;

myPeople = Application("Contacts").people.whose({ _and: [{lastName: "Doe" },{firstName: "John"}] });

for (i in myPeople) {
    person = myPeople[i];

    if (person.image() == null) continue;

    var data = person.image();

    var file = Path("/var/tmp/test.tiff");

    app.openForAccess(file, { writePermission: true });
    app.setEof(file, {to:0} ); // reset length
    app.write(data, {
        to: file,
        //as: 'data',
    });

    app.closeAccess(file);

    // result: file with 2 bytes ("<>")
}

Solution

  • Here is the JavaScript version, using the Objective C bridge and AddressBook framework. Bonus: conversion to PNG.

    ObjC.import("AddressBook")
    ObjC.import("AppKit")
    
    person = $.ABAddressBook.addressBook.me
    filename = $("~/Desktop/"+ person.displayName.js +".png").stringByExpandingTildeInPath.js
    
    image = $.NSImage.alloc.initWithData(person.imageData)
    imageData = $.NSBitmapImageRep.imageRepWithData(image.TIFFRepresentation)
    png = imageData.representationUsingTypeProperties($.NSPNGFileType, $())
    png.writeToFileAtomically(filename, false)