A reader asked me how he could show a random image to visitors. This is simple enough, so I thought I'd show an example of that along with an example of how you could rotate over a set of images and ensure the user sees each one.

First, here is an example of how to display a random image from a directory.

<!--- Get full path to images. ---> <cfset imageDirectory = expandPath(".")>

<!--- Get directory ---> <cfdirectory action="list" directory="#imageDirectory#" name="images" filter="*.jpg">

<!--- Do we have any images? ---> <cfif images.recordCount gt 0>

<!--- How many images? ---> <cfset totalImages = images.recordCount>

<!--- Pick one ---> <cfset pickedIndex = randRange(1, totalImages)>

<!--- get the file ---> <cfset image = images.name[pickedIndex]>

<!--- display it ---> <cfoutput><img src="#image#"></cfoutput>

</cfif>

In this example, I get a directory of images using the cfdirectory tag. You could also use a database of images. Since both return a ColdFusion query object, the only thing you would need to change is the first two lines. Outside of that though the rest of the code is trivial. Check to see we have any images, and then use the randRange() function to select a random row. Simple, right? Now look at a slightly different version.

<cfapplication name="img" sessionManagement="true">

<!--- Get full path to images. ---> <cfset imageDirectory = expandPath(".")>

<!--- Get directory ---> <cfdirectory action="list" directory="#imageDirectory#" name="images" filter="*.jpg">

<!--- Do we have any images? ---> <cfif images.recordCount gt 0>

<!--- How many images? ---> <cfset totalImages = images.recordCount>

<!--- param a session var ---> <cfparam name="session.pickedIndex" default="0">

<!--- Add one to the index ---> <cfset session.pickedIndex = session.pickedIndex + 1>

<!--- if past end, restart ---> <cfif session.pickedIndex gt images.recordCount> <cfset session.pickedIndex = 1> </cfif>

<!--- get the file ---> <cfset image = images.name[session.pickedIndex]>

<!--- display it ---> <cfoutput><img src="#image#"></cfoutput>

</cfif>

In this example, we don't select a random image. Instead, we use a session variable named pickedIndex. We increment the value on every hit, and if the value is higher than the number of images in the query, we reset it to 1. This means that as the user visits the page, they will see each image in order.