Get image path on disk with image style applied

Public

This is similar to rendering the image with an image style applied, but you can stop one step short and just get the path to the rendered file on the hard drive. Typically rendering the image with an image style returns an `<img ... />` tag, but for my project I wanted the actual file on the drive.

</> CopyGet raw version
php
  1. // Replace IMAGE_STYLE with the key for your image style (found in your site
  2. // at admin/config/media/image-styles), and FIELD_NAME with the field holding
  3. // the image you want to render.
  4. $image_style = 'IMAGE_STYLE';
  5.  
  6. // Get the images field
  7. $images = field_get_items('node', $node, FIELD_NAME);
  8.  
  9. if ($images) {
  10. // Get the first image only
  11. $image = reset($images);
  12.  
  13. // Get the URI of the ImageCache modified version of the file (with image styles applied)
  14. // The URI will be in Drupal form, either 'public://…' or 'private://…'
  15. $final_image_uri = image_style_path($image_style, $image['uri']);
  16.  
  17. // Get the path to the file on disc
  18. $final_image_path = drupal_realpath($final_image_uri);
  19.  
  20. // Generate the ImageCached file if it doesn't already exist
  21. // See http://api.drupal.org/api/drupal/modules!image!image.module/function/image_style_path/7
  22. // "The path returned by this function may not exist. The default generation
  23. // method only creates images when they are requested by a user's browser."
  24. if (!file_exists($final_image_path)) {
  25. $style_definition = image_style_load($image_style);
  26. image_style_create_derivative($style_definition, $image['uri'], $final_image_uri);
  27. }
  28.  
  29. // Now $final_image_path contains the path on disc for the rendered image
  30. }

Comments

willvincent's picture

This is good stuff. The only change I would suggest would be to use field_get_items() instead of assuming that there will always be something in the 0 delta for the desired field.

So, something like this:

  1. $images = field_get_items('node', $node, FIELD_NAME);

Then if you only ever wanted the first image:

  1. if ($images) {
  2. $image = reset($images);
  3. $image_uri = image_style_path($image_style, $image['uri']);
  4. $final_image_path = drupal_realpath($image_uri);
  5. }

or if you wanted to loop through all of them:

  1. if ($images) {
  2. $image_uris = array();
  3. $image_paths = array();
  4. foreach ($images as $image) {
  5. $image_uri = image_style_path($image_style, $image['uri']);
  6. $image_uris[] = $image_uri;
  7. $image_paths[] = drupal_realpath($image_uri);
  8. }
  9. }
thirdender's picture

Cool, thanks :-p Modified the code per your suggestion. It looks like `drupal_realpath` is deprecated… I think I might have to figure out a better way to find the path to the local file. The `file_create_url` function returns a complete URL ("http://...") instead of a file path…