使用JavaScript for Automation保存联系人的个人资料图片

时间:2016-08-07 15:08:13

标签: applescript javascript-automation jxa

我想将联系人的个人资料图片写入文件。

1)如何阅读TIFF图像?

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

在字典中,TIFFPicture是一个链接,但是当我点击它时,没有其他信息。 阅读时,值似乎为<>。 我如何将其作为图像阅读?

2)如何编写TIFF图像?

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

如果编写图像需要as:,应该指定什么类型?当我使用例如as: 'data'错误是“无法转换类型”。

示例:

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

2 个答案:

答案 0 :(得分:0)

关注foo's advice,这是一个有效的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)

答案 1 :(得分:0)

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