Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching image files to nodes programmatically in Drupal 7

Is it possible to add an image to a node programmatically?

like image 746
jantimon Avatar asked Feb 26 '11 20:02

jantimon


2 Answers

Here is an example code using which you can use with node_save

$filepath = drupal_realpath('misc/druplicon.png');
  // Create managed File object and associate with Image field.
  $file = (object) array(
    'uid' => 1,
    'uri' => $filepath,
    'filemime' => file_get_mimetype($filepath),
    'status' => 1,
  );

  // We save the file to the root of the files directory.
  $file = file_copy($file, 'public://');

  $node->field_image[LANGUAGE_NONE][0] = (array)$file;
`
like image 99
Daniel Wehner Avatar answered Nov 13 '22 15:11

Daniel Wehner


An easier way:

$filename = 'image.txt';
$image = file_get_contents('http://www.ibiblio.org/wm/paint/auth/gogh/gogh.white-house.jpg');
$file = file_save_data($image, 'public://' . $filename, FILE_EXISTS_RENAME);
$node->field_image = array(LANGUAGE_NONE => array('0' => (array)$file));
like image 32
Juan Pablo Novillo Avatar answered Nov 13 '22 16:11

Juan Pablo Novillo