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.
- Posted in:
- ColdFusion
2 comments
Leave a comment
If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Comment by RyanTJ – July 09, 2008
Comment by John Whish – July 09, 2008