Drupal Save Profile Image Programmatically

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.Screen Shot 2016-07-08 at 1.04.16 PM.png

  1. Note down the Field needs to be updated.
  2. Load the profile.
  3. Add Image field to the loaded profile object
  4. 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';
}

Leave a Reply

Your email address will not be published. Required fields are marked *