I am using this script to display random images from a folder. I have hundreds of images with significant filenames, So I’m looking for a way to display each image file name as an image caption. Is this possible?
this is the script Im using:
<?php
/*
By Matt Mullenweg > http://photomatt.net
Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
Latest version always at:
http://photomatt.net/scripts/randomimage
*/// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';
// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along
header('Location: '.$folder.$files[$rand]); // Voila!
?>
If all you want to do is continue to display a single random image then remove (or comment out so you can restore it if you later want to) the header line and at the end of the file add the following lines underneath it:
//header('Location: '.$folder.$files[$rand]); // Voila!
echo $files[$rand];
?>
<br />
<img src="<?php echo $folder.$files[$rand] ?>" />
You might want to add some css styling to set the display size of the image, and to format the caption above it.
Related
I've been displaying using the below code for a few years to display a random image in WordPress without any issues. The code broke today when I upgraded to PHP 7.4. I'm stuck on how to make the code work again or replace it with new code so that images from a directory are randomly displayed.
*Update: Broken code means images are you no longer being displayed. There are no error messages our outputs, just a blank section where the random image would usually display.
<?php
$folder = '';
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1;
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) {
if (preg_match('/\.'.$ext.'$/i', $file, $test)) {
$files[] = $file;
++$i;
}
}
}
closedir($handle);
mt_srand((double)microtime()*1000000);
$rand = mt_rand(0, $i);
header('Location: '.$folder.$files[$rand]); // Voila!
?>
The file is called rotate.php and it's located within the images directory. I call the rotate.php script from within the website's css style sheet using the following code:
background: #ffffff url(images/rotate.php) no-repeat center top;
Thanks for your help.
I have the following script for a webcam that upload pics every minute that runs with cron job.
It searches for images in a specific folder grabs and renames the latest, copy it to a new destination and delete the rest images.
Here is the script:
<?php
date_default_timezone_set("Europe/Athens");
//
//Watch Folder
$dir = "../upload";
//File extention to watch
$pattern = '/^.(jpg)$/';
//Newest file check
$newstamp = 0;
$newname = "";
if ($handle = opendir($dir)) {
while (false !== ($fname = readdir($handle))) {
// Eliminate current directory, parent directory
if (preg_match(' /^\.{1,2}$/',$fname)) continue;
// Eliminate other pages not in pattern
if (! preg_match('/\.(jpg)$/',$fname)) continue;
// -------------
// Collecting images
$pinakas[] = $fname;
}
// Sort Images
sort($pinakas);
// Count
$posot = count($pinakas);
// Take the before last position
if ($posot>1) $newname = $pinakas[$posot-2];
if ($posot==1) $newname = $pinakas[$posot-1];
}
closedir ($handle);
// $newname NEW IMAGE NAME
//COPY NEW IMAGE TO NEW PLACE
copy("../upload/$newname", "../camera1.jpg");
//DELETE IMAGES
$filesa = glob('../upload/*.jpg');
array_walk($filesa,'myunlink');
function myunlink($t)
{
unlink($t);
}
?>
Now i have a new ip camera that upload a pic every minute but everytime in a different folder like this:
Time: 10:01 ..upload/GSDGSDGSDGS/19-07-2018/001/jpg/10/01/05[R][0#0][0].jpg
Time: 10:02 ..upload/GSDGSDGSDGS/19-07-2018/001/jpg/10/02/06[R][0#0][0].jpg
Time: 10:03 ..upload/GSDGSDGSDGS/19-07-2018/001/jpg/10/03/07[R][0#0][0].jpg
How do i now make the script to search all the subfolders of ..upload for latest jpg grab it, copy it to new place and delete all the subfolders and .jpg images of the ..upload folder?
Any help appreciated.
You can do this with recursive function:
function getJpgImages($dir, &$pinakas = array()){
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if ( preg_match('/\.(jpg)$/',$path) )
$pinakas[] = $path;
} else if($value != "." && $value != "..") {
getDirContents($path, $pinakas);
}
}
return $pinakas;
}
and then remove your while loop and get images like this:
$pinakas = getJpgImages($dir);
I have a form that uploads data to the DB and this includes the path to the directory where images are uploaded. Everything works, except for the fact that the image won't display.
Viewing the source in my browser tells me that the image is found but I keep getting the broken image icon.
Here's my code:
$dir = "../uploaded_images/";
$filePath = $row['images_path'];
$fileArray = explode("*", $filePath);
if (count($fileArray) > 0) {
$image = $fileArray[0];
echo "<img src='$image' width='300px'>";
}
In the form you can upload multiple files. In the DB, the files get a random prefix then file name, like 3456456745654_imageName.jpg.
If multiple files are uploaded, they are split with an asterisk (*), which is why I'm exploding.
Then, to print only one image, I'm checking for the number of images relevant to a specific record then displaying only the first one.
PS. This code works for displaying all the images relevant to a selected image:
$dir = "uploaded_images/";
$filePath = $row['images_path'];
$fileArray = explode("*", $filePath);
foreach ($fileArray as $file) {
if (file_exists($dir . $file)) {
echo "<img class='images' src='$dir/$file' width='300px;'>";
}
}
But that's for a different page that displays a selected vehicle's information, including all images.
I need to show only one image per vehicle on the landing page that lists all vehicles.
Had to use the directory:
$dir = "../uploaded_images/";
$filePath = $row['images_path'];
$fileArray = explode("*", $filePath);
if (count($fileArray) > 0) {
$image = $fileArray[0];
if (file_exists($dir . $image)) {
echo "<img class='images' src='$dir/$image' width='300px;'>";
}
}
i have a form that create images (using imagejpeg, imagettftext and imagecreatefromjpeg) and save it on a folder in the server. What i need to do is to display ALL created images to another page, the newest on the top and so that the oldest is at the bottom. i have a form called formdisplay.php but it's just displaying a broken image and not newest to oldest. hope you can help me with this. really need to get this working. thanks in advance for your help.
i have read the posts but none of those worked for me.
Pull dedicated images from folder - show image + filename (strip part of filename + file-extension)
How can I display latest uploaded image first? (PHP+CSS)
getting images from the server and display them
Displaying images from folder in php
display image from server embedding php in html
formcreatesave.php
imagecopymerge($im, $img2, 10, 350, 0, 0, imagesx($img2), imagesy($img2), 100);
$date_created = date("YmdHis");//get date created
$img_name = "-img_entry.jpg"; //the file name of the generated image
$img_newname = $date_created . $img_name; //datecreated+name
$img_dir =dirname($_SERVER['SCRIPT_FILENAME']) ."/". $img_newname; //the location to save
imagejpeg($im, $img_dir , 80); //function to save the image with the name and quality
imagedestroy($im);
formdisplay.php
$dir = '/home3/site/public_html/Master/uploader/uploader';
$base_url = 'http://mysite.com/Master/uploader/uploader/20131027024705-img_entry.jpg';
$newest_mtime = 0;
$show_file = 'BROKEN';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (($file != '.') && ($file != '..')) {
$mtime = filemtime("$dir/$file");
if ($mtime > $newest_mtime) {
$newest_mtime = $mtime;
$show_file = "$base_url/$file";
}
}
}
}
print '<img src="' .$show_file. '" alt="Image Title Here">';
please feel free to edit my code. thanks :)
This goes after the while loop that creates the $images array (list of image filenames
foreach ($images as $image)
{
$filetime = filemtime("images1/$image");
$sortedimages[]$filetime => $image;
}
krsort($sortedimages);
echo "<pre>";
print_r($sortedimages);
echo "</pre>"
?>
Read images from folder.
Loop through them and insert into array with the key filetime of image.
Use krsort function to sort them according to date.
Loop and display them.
I think this link will help you:
http://forums.phpfreaks.com/topic/219466-php-displaying-images-from-folder-with-most-recent-first/
I am currently using http://photomatt.net/scripts/randomimage to display a random background image. I would like to have these images automatically rescale (dynamically?) according to the window or div width. Is this even possible? Code would be incredible if you have the time and ability. :)
Thanks in advance!
Here is the current random image code for your convenience:
<?php
// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';
// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double) microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along
header('Location: '.$folder.$files[$rand]); // Voila!
Well, I would probably take the javascript approach.
Load the image up behind the scenes in a hidden image element.
Bind to the image element's onload event so you know when it's completed.
Get the width/height of the image after it's loaded and use that to apply CSS/etc. to the page based on what the browser looks like, the image size is, etc.
Pseudo-Code:
var body = document.getElementsByTagName('body')[0];
var img = document.createElement('img');
img.src = 'random_image.php';
img.style.display = 'none';
img.onload = function(){
// modify the background styles based on your own conditions
};
body.appendChild(img);
If you really wanted to get fancy, you could bind to the window re-size event and continue to change the random image based on what the visible screen size, browser window size, etc. are.