2

I am trying to generate a URL for an image style, generated from an image in my theme directory:

$image_uri = drupal_get_path('theme', 'mytheme') . '/images/banners/projects-banner.jpg';
$banner_file = file_build_uri($image_uri);
$banner_url = image_style_url('my_image_style', $banner_file);

The $banner_url looks to be correct, however when I browse to it directly, I get a general Drupal error.

http://www.mysite.local/sites/default/files/styles/my_image_style/public/sites/all/themes/mytheme/images/banners/projects-banner.jpg

I had tried to pass $image_uri into image_style_url, but understand this need a URI and not a path. Can someone please point me in the right direction.

2
  • Something is amiss with your image file path. You don't usually see sites/default/files and sites/all/themes in the same URL. It looks like it's building the URL after the base URL for images in general instead of using the base URL for your installation. I'm not sure why.
    – Christia
    Commented Sep 5, 2017 at 17:48
  • The first part of the URL is correct (mysite.local/sites/default/files/styles/my_image_style) as all other image styles work with that (if the images are from content type fields) . I think the issue is because I'm using a path for an image that isn't stored in the managed files table - basically an image field for the content type. Commented Sep 6, 2017 at 9:25

1 Answer 1

2

You're right, the image_style_* functions only work with files in the managed file system. You can get round it by using the imagecache_external module, though, which takes remote images and stores them where we need them.

It might seem a little strange to be requesting local images as if they were remote, but this ensures the integrity of the image_style system without further hackery.

$image_uri = drupal_get_path('theme', 'mytheme') . '/images/banners/projects-banner.jpg';

$absolute_image_url = url($image_uri, array('absolute' => TRUE));
$banner_file = imagecache_external_generate_path($absolute_image_url);

$banner_url = image_style_url('my_image_style', $banner_file);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.