【发布时间】:2023-03-24 18:00:01
【问题描述】:
有什么方法可以在 OSX 上以编程方式更改用户帐户图像吗?
我知道我可以检索它,但可以像苹果在设置应用程序的帐户页面上那样更改它吗?
【问题讨论】:
标签: objective-c xcode macos cocoa user-accounts
有什么方法可以在 OSX 上以编程方式更改用户帐户图像吗?
我知道我可以检索它,但可以像苹果在设置应用程序的帐户页面上那样更改它吗?
【问题讨论】:
标签: objective-c xcode macos cocoa user-accounts
您可以使用通讯簿框架。您需要使用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。
【讨论】:
-[ABAddressBook me] 似乎返回 nil 如果您没有在通讯簿中明确添加自己的条目。 (因此在这种情况下这不起作用)。
您可以使用 /usr/bin/dsimport 命令找到一个文件并将其与当前记录合并,该命令可以从 NSTask 运行。这是一个如何使用 BASH 作为 root 执行此操作的示例,这也可以使用传递的凭据来完成
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
【讨论】:
我几乎可以肯定,您可以通过 OpenDirectory 界面执行此操作。请参阅本指南:
基本上你必须打开一个开放目录节点(比如 /Search 节点),然后为你的用户找到 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
【讨论】: