Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically changing the User's account image in OSX

Is there some way I can programmatically change the users account image on OSX?

I know I can retrieve it, but can it be changed like apple does on the account page in the settings app?

like image 787
Paul Peelen Avatar asked Jan 17 '23 05:01

Paul Peelen


2 Answers

You can use the Address Book framework. You need to use the me method to get the record for the current user, and then the setImageData: method to set the user's image:

#import <AddressBook/AddressBook.h>

@implementation YourClass
- (void)setUserImage:(NSImage*)anImage
{
    ABPerson* me = [[ABAddressBook addressBook] me];
    [me setImageData:[anImage TIFFRepresentation]];
}
@end

There's more detail here in the docs.

like image 62
Rob Keniger Avatar answered Jan 28 '23 09:01

Rob Keniger


You can path out to a file and merge it with the current record using the /usr/bin/dsimport command, which could be run from a NSTask. Here is an example of how to do so with BASH as root, this could be done with passed credentials as well

    export OsVersion=`sw_vers -productVersion | awk -F"." '{print $2;exit}'`
    declare -x UserPicture="/path/to/$UserName.jpg"
    # Add the LDAP picture to the user record if dsimport is avaiable 10.6+
    if [ -f "$UserPicture" ] ; then
        # On 10.6 and higher this works
        if [ "$OsVersion" -ge "6" ] ; then
            declare -x Mappings='0x0A 0x5C 0x3A 0x2C'
            declare -x Attributes='dsRecTypeStandard:Users 2 dsAttrTypeStandard:RecordName externalbinary:dsAttrTypeStandard:JPEGPhoto'
            declare -x PictureImport="/Library/Caches/$UserName.picture.dsimport"
            printf "%s %s \n%s:%s" "$Mappings" "$Attributes" "$UserName" "$UserPicture" >"$PictureImport"
            # Check to see if the username is correct and import picture
            if id "$UserName" &>/dev/null ; then
                # No credentials passed as we are running as root
                dsimport -g  "$PictureImport" /Local/Default M &&
                    echo "Successfully imported users picture."
            fi
        fi
    fi

Gist of this code

like image 35
acidprime Avatar answered Jan 28 '23 08:01

acidprime