以编程方式更改OSX中用户的帐户图像

时间:2012-03-15 11:42:06

标签: objective-c xcode macos cocoa user-accounts

我是否可以通过某种方式在OSX上以编程方式更改用户帐户图像?

我知道我可以检索它,但是可以像设置应用程序中的帐户页面上的苹果一样进行更改吗?

3 个答案:

答案 0 :(得分:4)

您可以使用地址簿框架。您需要使用me方法获取当前用户的记录,然后使用setImageData:方法设置用户的图像:

#import <AddressBook/AddressBook.h>

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

还有更多细节here in the docs

答案 1 :(得分:3)

您可以使用/ usr / bin / dsimport命令将路径输出到文件并将其与当前记录合并,该命令可以从NSTask运行。以下是以root身份使用BASH的示例,这可以通过传递的凭据来完成

    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

答案 2 :(得分:2)

我几乎可以肯定您可以通过OpenDirectory界面执行此操作。请参阅本指南:

https://developer.apple.com/library/mac/#documentation/Networking/Conceptual/Open_Directory/Introduction/Introduction.html#//apple_ref/doc/uid/TP40000917

基本上你必须打开一个开放目录节点(比如/搜索节点),然后为你的用户找到ODRecord,然后使用:

setValue:forAttribute:error
在ODRecord上

设置JPEGPhoto属性。

如果从命令行使用dscl查询此属性,您将看到属性的值:

dscl /Search read /Users/luser JPEGPhoto

我相信dscl工具使用Open Directory框架(或更老/更难使用/弃用的目录服务框架)来读取和写入用户记录的属性。您可以使用此工具和关联的框架读取和写入任何其他属性。我认为JPEGPhoto没有任何不同的原因。

/ Search节点可能是只读的(因为它是一种元节点)。不太确定。在写入记录之前,您可能必须显式打开相应的节点(例如/ Local / Default节点):

dscl /Local/Default read /Users/luser JPEGPhoto
相关问题