When we use the Profile 2 module and need to save the profile image field (existing), we can use profile2 functions and achieve the task.
- Note down the Field needs to be updated.
- Load the profile.
- Add Image field to the loaded profile object
- Save the profile.
function save_image_profile2($profile_id, $image_id){
// Load the profile object
$profile = profile2_load($profile_id);
// Image Field
$field = 'field_profile_pictire';
// Load the file
$val = array();
$file = file_load($image_id); // Load by fid
// $file = reset(entity_uuid_load('file', ['uuid' => $image_id])); // Load by uuid
if (!$file) {
return 'error';
}
$img_info = image_get_info(drupal_realpath($file->uri));
// Set the required attributes of the field
$val['und'][0]['fid'] = $file->fid;
$val['und'][0]['width'] = $img_info['width'];
$val['und'][0]['height'] = $img_info['height'];
//Save the profile
$profile->$field = $val;
profile2_save($profile);
return 'success';
}