Image Resizing with CCK, Imagefields, Imagecache and PHPTemplate

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:

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.

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.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options