Returns the URL for an image derivative given a style and image path.
$style_name: The name of the style to be used with this image.
$path: The path to the image.
$clean_urls: (optional) Whether clean URLs are in use.
The absolute URL where a style image can be downloaded, suitable for use in an <img> tag. Requesting the URL will cause the image to be created.
function image_style_url($style_name, $path, $clean_urls = NULL) {
$uri = image_style_path($style_name, $path);
// The token query is added even if the
// 'image.settings:allow_insecure_derivatives' configuration is TRUE, so that
// the emitted links remain valid if it is changed back to the default FALSE.
// However, sites which need to prevent the token query from being emitted at
// all can additionally set the 'image.settings:suppress_itok_output'
// configuration to TRUE to achieve that (if both are set, the security token
// will neither be emitted in the image derivative URL nor checked for in
// image_style_deliver()).
$token_query = array();
if (!config('image.settings')
->get('suppress_itok_output')) {
$token_query = array(
IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, file_stream_wrapper_uri_normalize($path)),
);
}
if ($clean_urls === NULL) {
// Assume clean URLs unless the request tells us otherwise.
$clean_urls = TRUE;
try {
$request = Drupal::request();
$clean_urls = $request->attributes
->get('clean_urls');
} catch (ServiceNotFoundException $e) {
}
}
// If not using clean URLs, the image derivative callback is only available
// with the script path. If the file does not exist, use url() to ensure
// that it is included. Once the file exists it's fine to fall back to the
// actual file path, this avoids bootstrapping PHP once the files are built.
if ($clean_urls === FALSE && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
$directory_path = file_stream_wrapper_get_instance_by_uri($uri)
->getDirectoryPath();
return url($directory_path . '/' . file_uri_target($uri), array(
'absolute' => TRUE,
'query' => $token_query,
));
}
$file_url = file_create_url($uri);
// Append the query string with the token, if necessary.
if ($token_query) {
$file_url .= (strpos($file_url, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($token_query);
}
return $file_url;
}