Helpful Information
 
 
Category: Post a PHP snippet
Random GD Image in Directory

Well since I lost all my PHP data in my drive E which dissapeared I have been starting to write different small scripts to pass time since I have nothing of mine on this computer anymore.

This script will display a random thumbnail image from the directory the script is in.



<?php

if ($handle = opendir('.')) {
$images = array();
while (false !== ($file = readdir($handle))) {
if (preg_match("/.(jpg|jpeg|gif|png)/i" $file)) {
$images[] = $file;
}
}
closedir($handle);
}
$file = array_rand($iamges);
if(preg_match("/.png/i", $file)) { $quality = 100; } else { $quality = 75; }
$max_width = 200;
$max_height = 200;
header('Content-type: image/jpeg');
list($width, $height) = getimagesize($file);
$ratio = ($width > $height) ? $max_width / $width : $max_height / $height;
if($width > $max_width || $height > $max_height) {
$new_width = $width * $ratio;
$new_height = $height * $ratio;
} else {
$new_width = $width;
$new_height = $height;
}
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($file);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_p, null, $quality);
imagedestroy($image_p);

?>


If you want to display a full random image its a matter of getting rid of the new widths and simply passing the old width and height in $image_p and imagecopyresampled()










privacy (GDPR)