Skip to content

Instantly share code, notes, and snippets.

@colorfield
Last active September 10, 2018 08:04
Show Gist options
  • Save colorfield/0edce8fe04de9fd40b1e to your computer and use it in GitHub Desktop.
Save colorfield/0edce8fe04de9fd40b1e to your computer and use it in GitHub Desktop.
Drupal 7 and 8 theme image
<?php
/**
* Drupal 7
*/
$fid = 1;
$uri = file_load($fid)->uri; // or fetched via the uri property of a field
$image_url = image_style_url('thumbnail', $uri);
$image = theme_image(array(
'path' => $image_url,
'alt' => 'my alt',
'title' => 'my title',
'attributes' => array(
'class' => 'my-image',
))
);
/**
* Drupal 8
* @see http://www.vdmi.nl/blog/drupal-8-rendering-image-programmatically
*/
$file = File::load(1);
$variables = array(
'style_name' => 'thumbnail',
'uri' => $file->getFileUri(),
);
// The image.factory service will check if our image is valid.
$image = \Drupal::service('image.factory')->get($file->getFileUri());
if ($image->isValid()) {
$variables['width'] = $image->getWidth();
$variables['height'] = $image->getHeight();
}
else {
$variables['width'] = $variables['height'] = NULL;
}
$logo_render_array = [
'#theme' => 'image_style',
'#width' => $variables['width'],
'#height' => $variables['height'],
'#style_name' => $variables['style_name'],
'#uri' => $variables['uri'],
];
// Add the file entity to the cache dependencies.
// This will clear our cache when this entity updates.
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($logo_render_array, $file);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment