Display a random image from a subdirectory

July 08, 2008

I recently need to pull a random image with a .jpg or .gif extension from a directory and display it. This can be done easily like this

<cfset imagepath = "images/gallery/" />
	
<cfdirectory directory="#ExpandPath(imagepath)#" 
  filter="*.jpg|*.gif" 
  name="qryImages"
  action="list" />

<img src="#imagepath##qryImages.name[RandRange(1, qryImages.RecordCount)]#" />

Note that the filter attribute uses the pipe character as a delimiter. A comma will not work! Thanks to Ben Nadel and Steve Withington for this tip.

Want to add the width and the height attributes?

Luckily ColdFusion 8 comes to the rescue.

<cfset imagepath = "images/gallery/" />

<cfdirectory directory="#ExpandPath(imagepath)#"
  filter="*.jpg|*.gif"
  name="qryImages"
  action="list" />

<cfset randomrow = RandRange(1, qryImages.RecordCount) />
<cfset myImage = ImageRead("#qryImages.directory[randomrow]#/#qryImages.name[randomrow]#") />

<img src="#imagepath##qryImages.name[randomrow]#" width="#ImageGetWidth(myImage)#" height="#ImageGetHeight(myImage)#" />

Want to get images from sub directories as well?

This time ColdFusion 7 (and above) has the answer. The recurse attribute of the cfdirectory tag was introduced in ColdFusion 7 which allows us to look in sub directories. With a little bit of string handling to get the web path we end up with this.

<cfset imagepath = "images/">
<cfdirectory directory="#ExpandPath(imagepath)#"
  filter="*.jpg|*.gif"
  name="qryImages"
  action="list"
  recurse="true" />

<cfset randomrow = RandRange(1, qryImages.RecordCount) />
<cfset myImage = ImageRead("#qryImages.directory[randomrow]#/#qryImages.name[randomrow]#") />
<cfset relativepath = "/" & ListChangeDelims(Replace(qryImages.directory[randomrow], GetDirectoryFromPath(GetBaseTemplatePath()), ""), "/", "\") & "/" />

<img src="#relativepath##qryImages.name[randomrow]#" width="#ImageGetWidth(myImage)#" height="#ImageGetHeight(myImage)#" />

I hope this helps someone.


2 comments

  1. Nice post, I did not know about the pipes either.

    Comment by RyanTJ – July 09, 2008
  2. The pipes delimiter is really useful, but for some reason is not listed on the livedocs. Filtering with regular expressions would be really cool!

    Comment by John Whish – July 09, 2008

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.