How to create a block with images in rotation

A client needed a simple solution to put several images in rotation, so that a random image will appear on every page load. The images are just a bunch of JPEGs or GIFs in a directory, not image nodes using the image module.

If you need to take out some images from rotation, then remove them from the directory. If you need to have more images in rotation, then just add new images to the directory. 

The following simple module does this task. Save it to a file named custom.module, and add a simple custom.info file and you are good to go.

function custom_block($op = 'list', $delta = 0, $edit = NULL) {
switch($op) {
case 'list':
$blocks[0] = array(
'info' => t('Custom image rotation'),
);
return $blocks;
case 'configure':
if ($delta == 0) {
$form['dir'] = array(
'#type' => 'textfield',
'#title' => t('Directory with images to rotate'),
'#default_value' => variable_get('custom_rotate_directory', path_to_theme() . '/images/rotation'),
);
}
return $form;
case 'save':
if ($delta == 0) {
variable_set('custom_rotate_directory', $edit['dir']);
}
return;
case 'view':
if ($delta == 0) {
$block = array(
'subject' => '',
'content' => custom_select_rotation_image(),
);
}
return $block;
}
}
/*
* Select all images in a directory
*/
function custom_list_rotation_images($path) {
$count = 0;
$img_dir = @opendir($path);
if (!$img_dir) {
return FALSE;
}
while (FALSE !== ($img_file = readdir($img_dir))) {
// add checks for other image file types here, if you like
if (preg_match("/(\.gif|\.jpg)$/", $img_file)) {
$images[$count++] = $img_file;
}
}
closedir($img_dir);
return $images;
}
/*
* Select one image from a set and rotate them randomly
*/
function custom_select_rotation_image() {
$path = variable_get('custom_rotate_directory', path_to_theme() . '/images/rotation');
$images = custom_list_rotation_images($path);
if (!$images) {
return NULL;
}
$count = count($images) - 1;
$random = mt_rand(0, $count);
$image_path = base_path() . $path . '/' . $images[$random];
return '<img src="' . $image_path . '" />';
} 

Contents: 

Comments

thanks

I had been trying to do a SELECT ... ORDER BY RAND() LIMIT 1, but with a really big dataset, it was taking a reeaaaly long time. This method is much faster. In fact, I used the file name returned by this method to do a SELECT file.nid ... WHERE file.filename = $images[$random], then a node_load on the result to get all the extra data associated with the photo. Thanks!