Drupal image cache API

Here's a couple of quick examples of how to use the image cache API.

Drupal 6

<?php
print theme('imagecache', $preset, $image['filepath'], $alt, $title,  $attributes);
 
// filepath is relative to base url (no leading slash)
// attributes is an array. For example:
 
print theme('imagecache', 'small', 'test.jpg', 'just a test image', 'test image', array('id'=>'small_image_id','class'=>'image','width'=>'100','height'=>'100'));
 
// http://drupal.org/node/163561
//get image dimensions
$image = imageapi_image_open("sites/default/files/imagecache/mobile_event_gallery/$photoname");
$height = $image->info['height'];
?>

Drupal 7

<?php
$img['fid'] = $fields['0']['fid']->content;
$img['object'] = file_load($img['fid']);
$img['url'] = is_object($img['object']) ? image_style_url('frontpage_artwork', $img['object']->uri) : '';
$img['info'] = image_get_info($img['url']);
$img['width'] = !empty($img['info']['width']) ? $img['info']['width'] : '';
$img['height'] = !empty($img['info']['height']) ? $img['info']['height'] : '';
 
// visiting $img[$url] will generate the image if it doesn't already exist.
?>

Drupal 8

<?php
$render_array = array();
$file = File::load(1);
$uri = $file->getFileUri();
$image = \Drupal::service('image.factory')->$uri;
 
if ($image->isValid()) {
  $render_array = array(
    '#theme' => 'image_style',
    '#width' => $image->getWidth(),
    '#height' => $image->getHeight(),
    '#style_name' => 'thumbnail',
    '#uri' => $uri,
  );
}
 
// Adds the file entity to the cache dependencies.
// This will clear the cache for this entity whenever it is updated.
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($render_array, $file);
 
?>

Tags

Internal References

External References

Article Type

General