Error message

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

Programmatically Render Image Style for Image Field with Drupal

Category: 

Drupal 6

Here is a function that you can pass an imagecache preset name and a drupal image file path to and it will try to build a derivative image from the preset name and return to you the path to the derived image:

function tf_imagecache_image_path ($presetname, $file_system_image_path) {
	
  if (!$preset = imagecache_preset_by_name($presetname)) { return; }
  
  $src = imagecache_create_path($presetname, $file_system_image_path);
  
  if (!file_exists($src)) {
    if (!imagecache_build_derivative($preset['actions'], $file_system_image_path, $src)) {
      watchdog("tf","tf_imagecache_image_path - imagecache_build_derivative failed - (" . $preset['actions'] . ") ($file_system_image_path) ($src)",WATCHDOG_WARNING);
    }
  }
  
return $src;
}

Here is an example usage using a CCK Filefield Image field I made called 'field_event_main_image':

$filepath = $node->field_event_main_image[0]['filepath'];
$event_img_src = tf_imagecache_image_path("my_imagecache_preset_name",$filepath);
$event_img_alt = $node->field_event_main_image[0]['data']['alt'];
$event_img_title = $node->field_event_main_image[0]['data']['title'];
$event_img = theme_image($event_img_src,$event_img_alt,$event_img_title);
print $event_img;

Drupal 7

In D7 it is easier to accomplish this. In the following example we'll take an image located at sites/default/files/clothing/hat.JPG and print out the 'thumbnail' for it.

$image = array(
  'style_name' => 'thumbnail',
  'path' => 'public://clothing/hat.JPG',
  'alt' => 'A Picture of a Hat',
  'title' => 'A Cool Hat'
);
print theme('image_style', $image);

The 'thumbnail' image style is a default image style that comes with D7, replace it with your custom image style's machine name to use custom image styles (a.k.a. image cache presets in D6).

Comments

Hi , I tried alot but I cant call imagecache image only I get the path of preset but no file name. pls advice thanks

tyler's picture

Hi irfan,

Are you having troubles with D6 or D7? I imagine it is for D6, but please clarify, thanks!

D7 version seems to fail if no preset has yet been generated; not the equivalent of imagecache_build_derivative()?

tyler's picture

Thanks for pointing this out Kenneth, I've noticed this behavior before if the preset hasn't been generated yet.

Worked like a charm.  Thanks!

As a side note, if anyone is using 1and1 hosting, you might need to add this to your settings.php to get ImageMagic to work:
putenv("MAGICK_THREAD_LIMIT=1");

Otherwise you might get the watchdog error:

ImageMagick reported error code 1. Message: libgomp: Thread creation failed: Resource temporarily unavailable in [yada yada yada]

Add new comment