Drupal - image_style_url doesn't create images

From: https://drupal.org/drupal-7.20-release-notes

In addition, any code which programmatically generates a link to an image derivative without using the standard image_style_url() API function will no longer work correctly if the image does not already exist in the file system, since the necessary token will not be present in the URL.

Instead you can do something like this;

$image_uri      = $node->field_image[LANGUAGE_NONE][0]['uri']; // or any public://my_image
$style          = 'my_style';
$derivative_uri = image_style_url($style, $image_uri);
$success        = file_exists($derivative_uri) || image_style_create_derivative(image_style_load($style), $image_uri, $derivative_uri);

$new_image_url  = file_create_url($derivative_uri);

One common mistake is that URIs are not properly formatted. Check that your URI parameter is prefixed with public://.

Bad Practice

$imageUrl = image_style_url('style_name', 'myimage.jpg');
$imageUrl = image_style_url('style_name', $node->field_x[$node->language][0]['filename']);

This outputs a URL to the styled image (with image token), but does not generate a styled image when it hasn't been previously generated.


Good Practice

$imageUrl = image_style_url('style_name', file_build_uri('myimage.jpg')); // changes to 'public://myimage.jpg'
$imageUrl = image_style_url('style_name', $node->field_x[$node->language][0]['uri']);

This outputs a styled URL, like the above, and generates a styled image if none exists.

Tags:

Media

Theming

7