There are a few ways to get files from nested subfolders.
The Finder has the entire contents
container property, but be aware that it can choke on large folder structures:
set theFolder to (choose folder)
tell application "Finder" to set theFiles to (get every document file in entire contents of theFolder as alias list)
set randomImage to (some item of theFiles)
System Events can also be used, although you would need to manually descend the directory tree. Like the Finder, you would also need to look for the desired type of files (images, etc) if you dont want everything (document types are mixed, for example):
set theFolder to (choose folder)
set theFiles to getFiles from theFolder # given extension:"png", UTI:"public.jpeg" -- or whatever
set randomImage to (some item of theFiles)
# Get files (optionally with the extensions or UTIs), recursively descending the directory tree
to getFiles from someItems given extension:extension : {}, UTI:UTI : {}
set foundList to {} -- this will be a list of found items
repeat with anItem in (someItems as list)
set anItem to anItem as text
tell application "System Events"
if class of disk item anItem is in {"folder", folder} then -- folder
set subFolders to (get path of disk items of folder anItem whose visible is true)
set foundList to foundList & my (getFiles from subFolders given extension:extension, UTI:UTI)
else -- file
if (UTI is {} and extension is {}) or ¬
(type identifier of file anItem is in UTI) or ¬
(name extension of file anItem is in extension) then
set foundList to foundList & {anItem as alias}
end if
end if
end tell
end repeat
return foundList
end getFiles
Your best bet might be the mdfind
shell script, which in addition to being fairly speedy, can match more generic UTIs (although the files do need to be indexed by Spotlight):
set theFolder to (choose folder)
set imageFiles to paragraphs of (do shell script "mdfind -onlyin " & quoted form of POSIX path of theFolder & space & quote & " kMDItemContentTypeTree == 'public.image'" & quote)
set randomImage to (some item of imageFiles) as POSIX file