How do I get the URL of an image inside a module directory?
Asked Answered
K

5

5

In the directory containing a custom module, I have a directory containing images.

How do I get the URL of those images?

Kagu answered 8/1, 2011 at 19:55 Comment(0)
P
4
drupal_get_path('module', $module_name);
Phycomycete answered 8/1, 2011 at 20:0 Comment(0)
H
3

The easiest way, like referred above, is to use the relative path to site root:

'/' . drupal_get_path('module', $module_name) . '/img1.jpg'

Using it without the trailing slash in the beginning would break it on multiple level aliases, e.g. http://www.your_site.dev/category/2012/11/02/

Hardie answered 25/12, 2012 at 13:53 Comment(1)
Thanks! drupal_get_path() without a preceding slash was messing me up.Cinchonine
G
1

A more complete example that works in Drupal 7 and 8. All other answers just show how to return the path to the module but not how to actually make a URL out of it.

<?php
$module_path = drupal_get_path('module', 'mymodule');
$image_path = "$module_path/images/img1.jpg";
$image_url = file_create_url($image_path);
Gloam answered 3/2, 2020 at 19:19 Comment(0)
H
0
// path
drupal_get_path('module', $module_name) . '/images';

file_create_url( drupal_get_path('module', $module_name) ) . '/images';

Hebrides answered 22/12, 2011 at 1:6 Comment(2)
Incorrect. The file_create_url will always work in relation to default/files not the module directory so the URLs would end up like your_site.dev/sites/default/files/sites/all/modules/your_module/… which is incorrect.Hardie
Yes, correct. file_code_url will return the URL under /sites/default/files. Thanks.Hebrides
T
0

To get proper URL of your image you need to append base_path() at the beginning of your image path. The correct URL would be:

$url = base_path() . drupal_get_path("module", "MY_MODULE") . "/image.png";

Temperature answered 20/6, 2017 at 23:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.