Log in

View Full Version : Resolved php random image



john0611
08-11-2009, 02:06 PM
Hi all,

This one has got me thinking?

Is there a way to make this array random for images with .jpg extension, instead of file names as list here?




<?php // random image by file
$images = array(
array('file' => '2000-09painting4',
'caption' => ''),
array('file' => '2000-09painting7',
'caption' => ''),


);
$i = rand(0, count($images)-1);
$selectedImage = "img/random/paintings/{$images[$i]['file']}.jpg";
$caption = $images[$i]['caption'];
if (file_exists($selectedImage) && is_readable($selectedImage)) {
$imageSize = getimagesize($selectedImage);
}
?>

Thank you for your help and suggestions.

John.

JShor
08-11-2009, 02:35 PM
You can retrieve an array of all images listed under one directory, and have them randomized.



<?php

$imgdir = '/myDir/'; // the directory, where your images are stored
$allowed_types = array('jpg','jpeg'); // list of filetypes you want to show
$dimg = opendir($imgdir);
while($imgfile = readdir($dimg)) {
if(in_array(strtolower(substr($imgfile,-3)),$allowed_types)) {
$a_img[] = $imgfile;
sort($a_img);
reset ($a_img);
}
}

$images = Array();

$totimg = count($a_img); // total image number
for($x=0; $x < $totimg; $x++) {
$size = getimagesize($imgdir.'/'.$a_img[$x]);

$halfwidth = ceil($size[0]/2);
$halfheight = ceil($size[1]/2);

echo 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />';

$images += array('file' => $a_img[$x],
'caption' => '');

}


$i = rand(0, count($images)-1);
$selectedImage = "img/random/paintings/{$images[$i]['file']}.jpg";
$caption = $images[$i]['caption'];
if (file_exists($selectedImage) && is_readable($selectedImage)) {
$imageSize = getimagesize($selectedImage);
}
?>


HTH:)

john0611
08-11-2009, 04:27 PM
Thanks for that JShor.