使用 JavaScript 保存联系人的个人资料图片以实现自动化

save contact's profile picture using JavaScript for Automation

我想将联系人的头像写入文件。

1) 如何读取TIFF图像?

字典描述图像属性:image (*TIFFPicture* or missing value) : Image for person.

在词典中,TIFFPicture 是 link,但是当我单击它时,没有其他信息。 阅读时,该值似乎是 <>。 如何将其作为图像阅读?

2)如何写入TIFF图像?

写入文件时,应该指定什么格式? 字典说:[as: type class] : how to write the data: as text, data, list, etc.

如果写图片需要as:,应该指定什么类型?当我使用例如as: 'data' 错误是 "Can't convert types"。

示例:

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 ("<>")
}

之后,这是一个可用的 AppleScript 版本:

tell application "Contacts"
    set {name:personName, image:personImage} to (get my card)
    set filePath to (((path to desktop folder) as text) & personName & ".tif")
    set theFile to open for access file filePath with write permission

    set eof of theFile to 0
    write personImage to theFile
    close access theFile
end tell

和自动化的等效 JavaScript(不工作):

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

var person = Application("Contacts").myCard()
var filePath = Path(app.pathTo("desktop") +"/"+ person.name() +".tif")
var theFile = app.openForAccess(filePath, { writePermission: true })

app.setEof(theFile, { to:0} )
app.write(person.image(), { to: theFile })
app.closeAccess(theFile)

这里是JavaScript版本,使用了Objective C桥和地址簿框架。奖励:转换为 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)