Cleanest/simplest method to render image fields with Drupal 7

A common issue when building a site in Drupal: you've got a $node, $vars['node'], or $form_state['node'] and need to render an image (with image style) from one of the fields. I am building a custom form in this instance, and need to show the first image stored in some loaded nodes.

  // Get the node loaded via node_load into $node.
  // Use field_get_items to get the correct field data.
  // Use current() to get the first item in the returned array.
  $field_picture = current(field_get_items('node', $node, 'field_picture'));
  // Reuse the field data since it already contains 'alt' and 'title'.
  // Add style_name and path.
  $field_picture['style_name'] = 'image_style';
  $field_picture['path'] = $field_picture['uri'];
  // Render the image to HTML using the field data.
  $picture = theme('image_style', $field_picture);

If you are going to be using the above code often, you should probably put in an function in a custom site module.


what a great post, just signed up to your RSS feed and hope to read more of your posts in the future. keep it up!

How do you apply an image style in a tpl.php?

ie with <?php print render($content['field_image']); ?> or <?php print render($content['uc_product_image']); ?>

I suggest you handle the render in a preprocess function to keep complex code out of the tpl.

THX a LOT!!!!!!