Programmatically save image and add it as image field to a node

Public

Pass the loaded node object and the full url to the file that you want to save. The file is added to the temp directory and than saved to the node as though you had added it though the node form file/image upload.

Get raw version
php
  1. function save_image_to_node($node, $file_path) {
  2. global $user;
  3. $file_temp = file_get_contents($file_path);
  4.  
  5. $file_name_display = $nid . '_' . $user->uid; // This simply provides a default name. Change as needed.
  6.  
  7. // Saves a file to the specified destination and creates a database entry.
  8. $file_temp = file_save_data($file_temp, 'public://' . 'file_name_display', FILE_EXISTS_RENAME);
  9.  
  10. $node->field_image = array(
  11. 'und' => array(
  12. 0 => array(
  13. 'fid' => $file_temp->fid,
  14. 'filename' => $file_temp->filename,
  15. 'filemime' => $file_temp->filemime,
  16. 'uid' => 1,
  17. 'uri' => $file_temp->uri,
  18. 'status' => 1,
  19. 'display' => 1
  20. )
  21. )
  22. );
  23. $node = node_submit($node);
  24. node_save($node);
  25. }