Last updated March 6, 2012. Created on August 1, 2007.
Edited by kingandy, NancyDru, lisarex, LeeHunter. Log in to edit this page.

Imagecache is a module that lets you make different sized alternatives of the same images. It requires an image manipulation library such as GD2 or ImageMagick and requires clean urls to be enabled. You can use imagecache with any image uploaded to Drupal, so you can use it with Image module as well as normally uploaded images using the Upload module, but the most common way is to use it with CCK and Imagefield.

View a screencast on using Imagefield and Imagecache.

One useful example is in a community site with many users. Users could upload a user picture that is for example, a 240 pixel square. This may work great for user profile pages, but say you want to make some views of users in specific groups - 240 x 240 pixels may be too big for a view that lists of dozens of people. On these views you may want to make the pictures smaller - 120 x 120 pixels for example. Image cache gives you a way to accomplish this without having to manually resize each image.

Another example that we're going to demonstrate in detail is when you want to scale images down for a teaser and display them in their full size when viewing the whole content. Before proceeding, make sure you have installed and enabled Imagecache, CCK and Imagefield. Also create the content type with the Imagefield you'll want to resize. If you just want to edit a template manually to resize an image, you should scroll down to the end.

First login to Administer -> Site Building -> Image cache (this used to be Administer -> Site Configuration -> Image cache in older versions of the module). Then label a new namespace preset: for example "small" (no quotes) and click on the 'Create preset' button.

Then choose an action: scale, resize, or crop. Scale works well when you want to keep the aspect ratio, you only need to enter one of the dimensions in this case. Resize will allow you to produce images of any arbitrary size, even if that results in a distorted image. Crop will allow you to display only part of the image, I'll use the Drupal logo as an example:
Scaled to 50%:

Resized to 60x20:

Cropped to 50%x50%, both offsets set to top:

For this example, scale will suffice, so select it and click on the 'Update preset' button:

After that, give the preset a width and height, you can use a percentage to get sizes relative to the original image's size or enter an absolute value in pixels. In the first example example we would use 50% or 120 to make a 120 pixel square image. As the second example is more generic and you might be dealing with images of several sizes, the best choice would be to specify a maximum value for both width and weight the image displayed in the teaser.

Let's suppose you want to scale the maximum size of the image to be 48x48. To do that, you fill out the width and height, and set it to scale to fit inside dimensions, unless you don't care if one of the dimensions may actually end up greater than the specified value. Don't forget to click on the 'Update preset' button after setting the needed values.

Now that we've successfully created our preset namespace, we need to edit the desired CCK field to automatically resize the images. To accomplish that, first go to Administer -> Content Management -> Content Types. After that, click on the configure link for the content type that contains the content type that has the field you want to configure.

Then just select display fields and set Teaser to the desired preset and click on 'Submit' (in this case "small", you could also edit full if you wanted the images to always be resized, even when browsing the full content):

Voilà, now all images in a "testimage" field will be automatically scaled down to a maximum of 48x48. Below is the final result.

Preview:

Full view:

If you want to add manually an image and apply an imagecache preset on it, you need to add a code snippet to the desired .tpl.php file:

print theme('imagecache', $preset, $image['filepath'], $alt, $title, $attributes);

Below is an example in which I manually call Imagecache using the namespace small and printing file test.jpg on the root of the Drupal installation directory (the image path should always relative to it). The alt atribute is shown when the image cannot be displayed while the title attribute is meant to be displayed in a tooltip.

print theme('imagecache', 'small', 'test.jpg', 'just a test image', 'test image');

($alt, $title, $attributes are optional, $attributes intentionally omitted in the example, as it's not a very frequently used parameter).

Putting several of these practices together can lead to code such as this:

<?php if ($field_images[0]['view'] > '' ) : ?>
<?php foreach($field_images as $item) { ?>
<div class="images">
<?php print '<img src="/files/imagecache/medium/'.$item['filepath'].'" title="'.$item['title'].'" alt="'.$item['alt'].'">'; ?>
<?php print '<h3 class="img_title">'.$item['title'].'</h3>'; ?>
</div>
<?php } ?>
<?php endif; ?>

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

eikes’s picture

It's the new thing! Create stuff programmatically. In Drupal 6 this worked for me:

	// Preset
	$imagecachepreset = new stdClass ();
	$imagecachepreset->presetname = 'MYPRESETNAME';
	drupal_write_record('imagecache_preset', $imagecachepreset);
	
	// Action
	$imagecacheaction = new stdClass ();
	$imagecacheaction->presetid = $imagecachepreset->presetid;
	$imagecacheaction->module = 'imagecache';
	$imagecacheaction->action = 'imagecache_scale_and_crop';
	$imagecacheaction->data = array(
							'width' => '200',
							'height' => '200' 
						);
	drupal_write_record('imagecache_action', $imagecacheaction);

I just wanted to share this with everyone

mavimo’s picture

This work "partially", with this code if admin go to Imagecage UI don't find preset (but if it add a preset this appair). This is a problem for me, but i correct it with:

    // Preset
    $imagecachepreset = imagecache_preset_save(array('presetname' => 'MYPRESETNAME'));
    // Action
    $imagecacheaction = new stdClass ();
    $imagecacheaction->presetid = $imagecachepreset['presetid'];
    $imagecacheaction->module = 'imagecache';
    $imagecacheaction->action = 'imagecache_scale_and_crop';
    $imagecacheaction->data = array('width' => '200', 'height' => '200' );
    drupal_write_record('imagecache_action', $imagecacheaction);

Bye
Mavimo
____________
Drupal Italia official community webstite
My personal website (Drupal, CFD, OpenFOAM and so - Italian only)

mavimo’s picture

tylerwalts’s picture

I used mavimo's code above in a module's _install hook, and it worked great. On the flip side, for the _uninstall hook I used:


// Called in the _uninstall hook, to delete the imagecache preset(s) created in the _install hook:
imagecache_preset_delete(imagecache_preset_by_name('MYPRESETNAME'));

(This applies to the 6.x version)

joachim’s picture

Just confirming the above works perfectly. Thank you!!
Should definitely be added to the page.

betz’s picture

Thanks, i created a new subpage for this at

http://drupal.org/node/558664

celstonvml’s picture

Here's an example from a module I'm building

$scale_and_crop = array('131x131','83x83','60x45');
foreach ( $scale_and_crop as $dimensions ) {
        list($width,$height) = split('x',$dimensions);

        $preset_id = db_next_id('{imagecache_preset}_presetid');
        db_query('INSERT INTO {imagecache_preset} (presetid, presetname) VALUES (%d, \'%s\')', $preset_id, $dimensions);

        $action_id = db_next_id('{imagecache_action}_actionid');
        $data = array(
                'width'         => $width,
                'height'        => $height,
        );
        db_query("INSERT INTO {imagecache_action} (actionid, presetid, weight, action, data) VALUES (%d, %d, %d,'%s', '%s')", $action_id, $preset_id, 0,
'imagecache_scale_and_crop', serialize($data));
}
cache_clear_all('imagecache:presets', 'cache');

What would be awesome is if the preset table contained a "module" field, similar to that found in node types and taxonomy vocabularies. You could then select by module to remove them in hook_uninstall.

aeontech’s picture

The $attributes should be an array of additional attributes to the image. 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'));
mmrtnt’s picture

I am going nuts trying to instantiate this in an external PHP file that I would like to call from inside Drupal:

 <?php
  
  require_once '../../../includes/bootstrap.inc';
  require_once '../../../includes/theme.inc';
   
  $output = "
    <html>
       <body>";

  $output.= theme( 'imagecache', 'detail_thm', 'images/motel_wright-1.1.png', 'Wright Motel', 'Wright Motel' );

  $output.= "
       </body>
    </html>";

   print $output;

?>

I'm sure what I've got here is totally wack; if anyone can get me pointed in the right direction, I'd greatly appreciate it.

mmrtnt’s picture

I've solved this myself.

What I really wanted to do was call an external page with my own css, javascript, php & html and still have access to the Drupal modules.

I didn't have time to delve into the intricacies of Drupal and I didn't want to have to write a module, so there's probably a more elegant way to do this, but this is what I came up with.

First I created a static page with PHP filtering on, "node/10" let's say, and then put this inside it:

<?php
   include( 'relative_directory/myphp.html' );
?>

I turned off sections in chameleon.theme that interfered:

<?php

 $node = node_load(arg(1));
 if( $node->nid != 10 ) {
     $output  = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
     $output .= "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"$language\" xml:lang=\"$language\" dir=\"$direction\">\n";
     $output .= "<head>\n";
     $output .= " <title>". ($title ? strip_tags($title) ." | ". variable_get("site_name", "Drupal") : variable_get("site_name", "Drupal") ." | ". variable_get("site_slogan", "")) ."</title>\n";

     $output .= drupal_get_html_head();
     $output .= drupal_get_css();
     $output .= drupal_get_js();
     $output .= "</head>";
   }
?>

Now I can do pretty much whatever I want in myphp.html and still have access to things like "imagecache".

I put in some code to redirect back to the main page if several conditions are not satisfied, to provide a smidgen of security.

You can see the results at southrustern.com by clicking on any image in the blog section.

Hope this helps someone else.

(Edit, changed title)

starapple’s picture

I'm at a bit of a loss where to find info on Imagecache as it relates to Drupal 7.x. I see where it's supposed to be a part of core in Image but there is no user interface. I'm trying to install the Media Mover module(s) but have encountered the message: Imagecache (missing), Imagecache_ui (missing).

HELP!!

rwilson0429’s picture

For D7, enable image module in core then, go to admin/config/media/image-styles

ReggieW

Sk8erPeter’s picture

In Drupal 5 and 6, one could use the theme_imagecache() function.
The Drupal 7 and 8 alternative is theme_image_style() as a core module function.

Here's a short article about the usage of theme_imagecache() and theme_image_style() too.

escoles’s picture

I don't have a D7 install handy to check on, but try this: don't look for imagecache -- look for image settings, or something similarly generic. When things go into core, they don't necessarily go in with the same name or as the same set of modules. So you may not find the term "imagecache" anywhere, but the features are there, integrated into other places?