Setting an Address Book Picture with AppleScript

[This information in this post is out of date. Please see Gravatar, AppleScript, and the OS X Address Book Revisited for more current information.]


In part 1, Gravatar, AppleScript, and Address Book Pictures, we covered the basics of getting a Gravatar URL with AppleScript. The end goal is to automatically update all of our Address Book pictures with Gravatars in one fell swoop.

There are a couple tricky things we need to solve to reach our goal. They aren’t difficult; just not well documented, if at all.

In this post I’ll show you how to update a contact picture with AppleScript.

Let’s get started.

We know from the Gravatar documentation that it returns images in jpeg format. Now according to the AppleScript dictionary for Address Book, the person class has an image element that is in TIFF format. So we’ll have to convert the image.

In addition, Address Book is very particular about how it gets an image. The only way I could make it work was to have the actual TIFF picture data loaded into a variable then set the contact’s picture to that. I couldn’t just refer to a file, even if it was already a TIFF.

Fortunately, there’s no need to go through a big conversion script or call on other applications. You can simply open a jpeg file from AppleScript and read the contents into a variable while coercing it to TIFF format.

Here is a demonstration script showing how it works:

-- Set an Address Book contact photo from a jpeg file.
-- Released under GPL.
-- by Doug Smith, https://smithsrus.com
--
-- This is for demonstration purposes. It only works on the first selected
-- contact in Address Book and contains little error checking. Note that
-- the picture displayed will not change until you select a different record
-- then come back to the original record so it can refresh.

tell application "Address Book"
	set AB_contacts to selection

	if number of items in AB_contacts = 1 then
		set one_contact to item 1 of AB_contacts

		set pict_file to choose file of type "JPEG" with prompt "Choose a jpeg file"
		open for access pict_file
		set pict_data to read pict_file as "TIFF"
		close access pict_file

		set image of one_contact to pict_data
	end if
end tell

It’s worth noting that my attempts to get the picture data into a variable Address Book accepted by means other than reading a file were not successful. For example, I tried using a shell call to curl to download a file and return the results to a variable. That would have been nice for our purpose of downloading a Gravatar image. If anyone has any further insight on that please let me know.

That’s all for this post. Stay tuned for part 3 when I’ll cover Detecting When Gravatar Has No Image to Match an E-mail Address. Then in part 4 we’ll put it all together with a Script to Update Address Book Contacts with Gravatar Images.

2 thoughts on “Setting an Address Book Picture with AppleScript”

Leave a Reply