Modifying Drupal 7 User Pictures in code

It took me a while to figure out how to modify or add a user picture from inside a custom module. Google was not much help. So here's the answer I found, hope it helps someone.

First, you need an actual Drupal file object. Something you could reference a file id from. Like $newbieFile->fid.

I referenced modules/user/user.module and includes/file.inc to figure this out.

$photo ="the actual image data."; //in my case it was the value of jpegPhoto from an ldap directory.
//Save the pic to a temporary file.
$writePic = file_save_data($photo);
// Now $writePic contains the file stdObj.

After that, just use user_save() in your module. Set $edit['picture_upload'] = $writePic; user_save() will pick that up and make everything work for you.

$edit = array(
'picture_upload' => $writePic
);
user_save($account,$edit);
Submitted by david.reagan on