Darren Mothersele

Software Developer

Warning: You are viewing old, legacy content. Kept for posterity. Information is out of date. Code samples probably don't work. My opinions have probably changed. Browse at your own risk.

Image Resizing with CCK, Imagefields, Imagecache and PHPTemplate

May 14, 2008

web-dev

If you have a CCK content type with an image field you get display options that allow you to change the image size on teasers and full node views. First you set up your image presets using the imagecache settings. I usually let users upload at any size, and deal with the resizing as required. Here's how to ensure you get best results from imagecache, and how to embed imagefield images into your PHPtemplates using the theme functions provided by imagecache:

Update: I recommend upgrading to the latest version of Imagecache - The interface is much improved and "crop and resize" are now available as a combined option.

In the imagecache options set up presets for each size you are going to need. You get several options for resizing. You want to use scale so the images are not distorted, and use outside dimensions so that the image is at least as big as your required thumbnail. Then use clip to remove any image outside of your thumbnail area. This means that your thumbnails are always the same size. I prefer this to using inside for the scale options, as that causes the images to come out at various different sizes. I like thumbnails to all be the same size, and cropping is usually acceptable.

I use the scale inside option to reduce pictures for screen size display. This works well for images used in full node templates as I'm not as fussy about making them all the same size.

Now you've got a CCK content type with an image field, and you have imagecache setup to give you the images at the size you need. Now you need to display them in your template.

The CCK field display options gives you the opportunity to select a size for the image as displayed in either the teaser or node view, but in your template you might want more control than this. That's when you need to turn to the theme functions provided by imagecache. In this code snippit I render a thumbnail from a $node object with an imagefield called event_photo:

<?php
print theme('imagecache', 'thumbnail', $node->field_event_photo[0]['filename'])
?>

In your own template substitute thumbnail with the imagecache preset name as required, and field_event_photo with your CCK field name.

You might want to link the image to something. Here's how you do this and render the correct Drupal path (it may have been aliased by an administrator):

<?php
print drupal_get_path_alias('node/'.$node->nid)
?>

Put that in an <a> tag around your themed image display code from before.