473,605 Members | 2,185 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Choose random image from dir and display it

I have a directory of images, called "random". In it are the following
files:

1.gif
2.gif
3.gif
4.gif

I use this script to choose a random image and display it:

$i = -2; // $i = -2 so that the directory files ("." and "..") won't be
counted.
if ( $dh = opendir( "images/random" ) ) {
while ( false !== ( $file = readdir( $dh ) ) ) {
$i++;
}
closedir( $dh );
$rand = rand( 1, $i );
$randimg = '<img src="images/random/' . $rand . '.gif" />';
}
print $randimg;

This works just dandy. However, I figure there must be a more efficient way
to count the number of files in a directory. Is there a directory's
equivalent of a function like file()? Or is my script the only way to count
the files?

Thanks.
- JP
Jul 17 '05 #1
4 3410
You probably find it safer to keep doing it the way you are.

Or instead modify it to build an array containing filenames and then
randomly pick an entry from the array. This is to account for if a file
is ever removed, no errors would occur.
kingofkolt wrote:
I have a directory of images, called "random". In it are the following
files:

1.gif
2.gif
3.gif
4.gif

I use this script to choose a random image and display it:

$i = -2; // $i = -2 so that the directory files ("." and "..") won't be
counted.
if ( $dh = opendir( "images/random" ) ) {
while ( false !== ( $file = readdir( $dh ) ) ) {
$i++;
}
closedir( $dh );
$rand = rand( 1, $i );
$randimg = '<img src="images/random/' . $rand . '.gif" />';
}
print $randimg;

This works just dandy. However, I figure there must be a more efficient way
to count the number of files in a directory. Is there a directory's
equivalent of a function like file()? Or is my script the only way to count
the files?

Thanks.
- JP

Jul 17 '05 #2
neur0maniak <us****@neur0ma niak.co.uk> wrote in news:41830267$0 $43631
$e*******@ptn-nntp-reader04.plus.n et:
You probably find it safer to keep doing it the way you are.

Or instead modify it to build an array containing filenames and then
randomly pick an entry from the array. This is to account for if a file
is ever removed, no errors would occur.


Try this, as described above. Forget where I found the code but it works
just fine. $dirpath should be a fullpath to the appropriate directory and
requires a slash at the end... or you can add it to the couple of lines
in between the path and the image filename. Everything in the directory
except those in the if statement will be put into the array.

$dir_contents = array();
$d = dir($dirpath);
while ( $crnt_file = $d->read() ) {
if ($crnt_file == "." || $crnt_file == ".."
|| is_dir($dirpath .crnt_file))
continue;
$dir_contents[] = $dirpath.$crnt_ file;
}
$d->close();
Jul 17 '05 #3
Fox
kingofkolt wrote:
I have a directory of images, called "random". In it are the following
files:

1.gif
2.gif
3.gif
4.gif

I use this script to choose a random image and display it:

$i = -2; // $i = -2 so that the directory files ("." and "..") won't be
counted.
if ( $dh = opendir( "images/random" ) ) {
while ( false !== ( $file = readdir( $dh ) ) ) {
$i++;
}
closedir( $dh );
$rand = rand( 1, $i );
$randimg = '<img src="images/random/' . $rand . '.gif" />';
}
print $randimg;

This works just dandy. However, I figure there must be a more efficient way
to count the number of files in a directory. Is there a directory's
equivalent of a function like file()? Or is my script the only way to count
the files?

Thanks.
- JP


php 4.3 or greater:

$imgGroup = glob("images/random/{*.jpg,*.gif,*. png}", GLOB_BRACE);

echo "
<img src = {$imgGroup[rand(0, count($imgGroup )-1)]} />
";

Fox
**************

Jul 17 '05 #4
"kingofkolt " <je**********@c omcast.net> wrote in message news:<WMBgd.340 547$D%.310394@a ttbi_s51>...
I have a directory of images, called "random". In it are the following
files:

1.gif
2.gif
3.gif
4.gif

I use this script to choose a random image and display it:

$i = -2; // $i = -2 so that the directory files ("." and "..") won't be
counted.
if ( $dh = opendir( "images/random" ) ) {
while ( false !== ( $file = readdir( $dh ) ) ) {
$i++;
}
closedir( $dh );
$rand = rand( 1, $i );
$randimg = '<img src="images/random/' . $rand . '.gif" />';
}
print $randimg;

This works just dandy. However, I figure there must be a more efficient way
to count the number of files in a directory. Is there a directory's
equivalent of a function like file()? Or is my script the only way to count
the files?

Thanks.
- JP


Yes. You can do all that in a couple lines:

$file = array_rand(glob ("images/random/*.gif"));
echo "<img src=\"$file\">" ;
Jul 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2091
by: lucy | last post by:
Hello comp.lang.js.I need a script to rotate a background image on each newpage load, given the id of the element and a list (array?)of 2 or more image paths ("img1.jpg", "img2.jpg", ...).Actually, depending on how I write the HTML, I guess I'dneed the script to set style.backgroundImage or src.I'd need to run it on a few elements, something like:setRandomBgImg('thingy1', ('img1a','img1b', ...) )setRandomBgImg('thingy2', ('img2a','img2b',...
4
2743
by: tshad | last post by:
I am trying to set up an Image authorization where you type in the value that is in a picture to log on to our site. I found a program that is supposed to do it, but it doesn't seem to work. It should put a blue and yellow box on the page with "This is a test" as part of the picture. But what I get is a broken Gif. The other problem is that I can't view the source???? The view source is disabled for this page. What causes this?
7
2342
by: Spartanicus | last post by:
Afaik the use of a <noscriptelement is frowned upon nowadays. For a JS random image changer I tried to use a replacement by having the script change the HTML src attribute value of an img element. The trouble is that in some situations like over slow connections (on initial load when the JS is in an external file), or with a slow client the image specified in the HTML starts to load and display before it's changed by the script. This I'm...
4
3072
by: Kim | last post by:
Random image downloader for specified newsgroup. Hi I'm writing a small script that will download random images from a specified newsgroup. I've imported yenc into the script but I can't open the image or save it. This is my first script so be gentle! Heres the script ####random group downloader#### import nntplib import string, random import mimetools import StringIO
0
1523
by: Kim | last post by:
Random image downloader for specified newsgroup. Hi I'm writing a small script that will download random images from a specified newsgroup. I've imported yenc into the script but I can't open the image or save it. This is my first script so be gentle! Heres the script ####random group downloader#### import nntplib import string, random import mimetools import StringIO
1
1768
by: KoRnDragon | last post by:
I need a Javascript function that will display X random images on a page that also doesn't display the same image twice. Bonus points if it grabs the max array from the folder and sets it. Even more points if it grabs all the image names from the folder. Thanks in advance!
1
2649
by: Sahus Pilwal | last post by:
Hi, I hope someone can help me with this. I'm new to .NET and in fact server side programming and have a small query I'm sure... I'm using the System.IO Namespace with a For - each and If then statement to randomly generate images to display in a <asp:image/image control. The random images are selected from a fixed folder on the webserver. All works fine but only if the images in the folder are of image format say jpg or gif. However...
8
2432
by: Kentor | last post by:
Hello, I have users that submit images to my website. By default I choose to make the width bigger than the height because usually pictures are taken horizontally... But in some cases people take pictures vertically so what I'm getting at is... can I know whether an image was taken horizontally or vertically so I can make the proper width/ height lengths so that it looks nice and not kinda weird... because if you make the width bigger...
10
3399
by: lifity | last post by:
hi, i am stuck on part of my project and very new to VB. i had cut my picture into 6 equals part but need to display them randomly, without repeating the same part of the pic again, in random sequence. eg, pic1,pic2,pic3,pic4,pic5,pic6 to ==> pic3,pic2,pic6,pic1,pic5,pic4 below are part of my code Dim theImage(0 To 7) As Object Dim myArray(0 To 7) As Object
0
7937
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8076
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8290
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5889
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5446
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3960
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2438
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1546
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1274
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.