I have code on how to random images on refresh however i wan it to be like when i click a button a random images shows up how do i do that?
Here's the code to random images:
<?
$imglist='';
//$img_folder is the variable that holds the path to the banner images. Mine is images/tutorials/
// see that you don't forget about the "/" at the end
$img_folder = "images/tutorials/";
mt_srand((double)microtime()*1000);
//use the directory class
$imgs = dir($img_folder);
//read all files from the directory, checks if are images and ads them to a list (see below how to display flash banners)
while ($file = $imgs->read()) {
if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
$imglist .= "$file ";
} closedir($imgs->handle);
//put all images into an array
$imglist = explode(" ", $imglist);
$no = sizeof($imglist)-2;
//generate a random number between 0 and the number of images
$random = mt_rand(0, $no);
$image = $imglist[$random];
//display image
echo '<img src="'.$img_folder.$image.'" border=0>';
?>
Work with JavaScript:
document.getElementById('the-img-id').onclick = function() {
var randomInt = Math.round(Math.random() * 12); // 12 is the max
this.src = '/path/to/images/img-'+randomInt+'.jpg'; // replace the src
}
This works with /path/to/images/img-1.jpg.
You can also make an array:
var myImages = [
'foo.jpg',
'bar.jpg',
'something.jpg',
'someotherting.jpg',
'ahhhanpng.png'
];
// select a element with id="the-img-id"
document.getElementById('the-img-id').onclick = function() {
var randomInt = Math.round(Math.random() * myImages.length-1 ); // Create random number
this.src = '/path/to/images/'+myImages[randomInt]; // replace the src with the new img
}
Look at the comments (after //) and google some code and you will use this succesfully.
you will need to use javascript. Use getElementById("idOfImageElement").src = "newSrc".
Related
<div id = "listwrapper">
<ul id = "mylist">
<?php
$images = glob("sorted/2017/*.jpg");
$i = 0;
foreach((array_reverse($images)) as $image){
if ($i == 0){
echo "<li>";
}
$i++;
echo'<img id="BR" src="'.$image.'">;
if($i==4){
echo"</li>";
$i = 0;
}
}
?>
</ul>
<div>
The above script works fine and outputs a <li> tag with 4 images in each one. with about 80 images in total.
Now I'm trying to use next() and closest() to display the next <img> in the <li> tag when the image is clicked. or if it is the last <img> in the <li>, then skip to the next <li>? seems like it would be easier to change the script and just put each image in its own <li> tag..
$('#mylist li img').click(function(){
var el = document.getElementById('BR');
var big = document.getElementById('BRBIG');
var img = document.getElementById('mylist li img');
imageClicked = $(this).closest('li');
big.src = imageClicked.find('img').next().next().attr('src');
$('#brbigcon').show('fadein');
$('#BRBIG').show(300);
$('#fs').show(300);
});
Is there someway to implement closest('img') instead of closest ('li')?
Try this:
<div id = "listwrapper">
<ul id = "mylist">
<?php
$images = glob("sorted/2017/*.jpg");
$i = 0;
foreach((array_reverse($images)) as $image){
if ($i == 0){
echo "<li>";
}
$i++;
echo '<img class="BR" src="'.$image.'">';
if($i==4){
echo "</li>";
$i = 0;
}
}
?>
</ul>
<div>
Jquery:
$('#mylist .BR').click(function(){
var src = $(this).attr('src');
var big = $('BRBIG');
big.attr('src', src);
$('#brbigcon').show('fadein');
$('#BRBIG').show(300);
$('#fs').show(300);
});
A piece of advice. In your html, if the amount of images is not a multiple of 4, the last li never gets closed. Here you have another approach to solve it...
<div id = "listwrapper">
<ul id = "mylist">
<?php
// Get the array of image urls.
$images = array_reverse(glob("sorted/2017/*.jpg"));
// Create the html `img` element of each image.
$imgs = array_map(function($v) { return "<img class=\"BR\" src=\"".$v."\">"; },$images);
// Chumk the array in groups of 4 and put each group inside of a `li` element.
$imgsli = array_map(function($v) { return "<li>".implode("",$v)."</li>"; },array_chunk($imgs,4));
// Print all the `li` elements.
echo implode("",$imgsli);
?>
</ul>
<div>
About the jquery, this would be my approach...
$('#mylist li img').click(function() {
var $nextImg;
if ($(this).next('img').length > 0) { // There's more img in current li, get the next one.
$nextImg = $(this).next('img');
}
else {
if ($(this).closest('li').next('li').length > 0) // There's more li's, go to the first image of the next one.
$nextImg = $(this).closest('li').next('li').find('img:first');
else // We are in the last div, go to the first image.
$nextImg = $('ul#mylist li:first img:first');
}
// Now $nextImg is the jQuery object of the right next image. Do what you need to show it.
...
});
With this you get the right next image according to your indications. Just add the code you want to show the image, etc.
I hope it helps
I am totally new to stackoverflow. I'm trying to adjust an excisting script in which an folder containing photo and video is getting loaded and displayed like a slideshow.
I'd like to add the option to load webpages also. Is there any easy way to do this?
Thank you so much.
This is my code:
<?php
include "class.getFiles.php";
$images = new getFiles();
// list of all files in the images folder (includes videos)
$imageArray = $images->getImageArray();
$sortedImages = new sortFiles();
$sortedImages->sortImageArray($imageArray);
// remove files not in the correct time period
$imageArray = $sortedImages->getImageArray();
$randImage = $sortedImages->randomImageNum();
$fileName = $imageArray[$randImage];
$info = new SplFileInfo($fileName);
?>
<!DOCTYPE html>
<html>
<head>
<title>Fiction Slideshow</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<?php
if($info->getExtension() == "mp4")
{
echo '<video id="vid" class="videoDisplay" autoplay>
<source src="images/'.$fileName.'" type="video/mp4">
Your browser does not support the video tag.
</video>';
echo '<script type="text/javascript">
var vid = document.getElementById("vid");
vid.addEventListener("ended", function(){
window.location.reload();
});
</script>';
}
else
{
echo '<img class="imageDisplay" src="images/'.$fileName.'" />';
echo '<script type="text/javascript">
setTimeout(function(){
window.location.reload();
}, 30000);
</script>';
}
?>
</body>
</html>
This is the class.getFiles.php file that the other script calls.
<?php
class getFiles{
protected $dir;
protected $imageArray;
function __construct()
{
$this->get_dir();
$this->get_images();
}
protected function get_dir()
{
$this->dir = getcwd();
}
protected function get_images()
{
if(count(scandir($this->dir."/images")) != 2)
{
$this->imageArray = scandir($this->dir."/images");
}
else
{
die("There are no files in the directory");
}
}
public function getImageArray()
{
return $this->imageArray;
}
}
class sortFiles{
protected $sortedImageArray = [];
public function sortImageArray($imageArray)
{
foreach ($imageArray as $imageFile )
{
if($imageFile !== ".." && $imageFile !== ".")
{
$imagePath = $imageFile;
$imageFile = (substr($imageFile, 0, -4));
$BeginningPos = strpos($imageFile, '_');
$beginningDate = (substr($imageFile, 0, $BeginningPos));
$beginningDateformatted = str_replace("-","/", $beginningDate);
$stringToStartTime = strtotime($beginningDateformatted);
$EndingPos = strpos($imageFile, '_', $BeginningPos + strlen('_'));
$EndingPos = $EndingPos + 1;
$EndingDate = (substr($imageFile, $EndingPos));
$EndingDateformatted = str_replace("-","/", $EndingDate);
$stringToEndTime = strtotime($EndingDateformatted);
$time = time();
if($time <= $stringToStartTime && $time >= $stringToEndTime)
{
array_push($this->sortedImageArray, $imagePath);
}
}
}
}
public function getImageArray()
{
if(count($this->sortedImageArray) != 0)
{
return $this->sortedImageArray;
}
else
{
die("There are no files in the time range");
}
}
public function randomImageNum()
{
$imageArrayLength = count($this->sortedImageArray);
$imageRand = rand(0, $imageArrayLength-1);
return $imageRand;
}
}
?>
Well you can save the web pages as links within your media folder. For example if you want to display the web page http://www.example.com, then you can create a file webpage1.txt inside the media folder. This file can have the link http://www.example.com.
In your code you can add a new condition that checks if the file type is txt. If the file type is txt, then your code can read the link inside the file and display the link using an iframe. The following code should work:
else if(strpos($fileName, "weblink") !== false)
{
/** The path to the web page link */
$file_path = (getcwd() . DIRECTORY_SEPARATOR . "images" . DIRECTORY_SEPARATOR . $fileName);
/** Read contents of file */
$web_page_link = file_get_contents($file_path);
/** Display the link in iframe */
echo "<iframe src='".$web_page_link."' width='100%' height='100%'></iframe>";
}
The above code should go above the else statement
I have the following code that is functional that will randomize the photos I have in my 'photos' folder each time the refresh button is clicked. I know this may not be the most efficient way for this to be coded but for my matter it works. I am looking for help regarding my PHP code that will make the photos more random. I currently have 200+ pictures in the folder and often get repeated pictures more than I'd like. What changes to it can I make? (PS. ignore the AJAX/JavaScript I was playing around with)
<html>
<head>
<title>Pictures!</title>
<style type="text/css">
body{ background-color:D3DFDE; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<div id='main'>
<?php
function randomimages(){
$dirname = isset($_REQUEST['dir'])? $_REQUEST['dir'] : './photos/';
$numimages = isset($_REQUEST['num'])? $_REQUEST['num'] : 1;
$pattern = '#\.(jpg|jpeg|png|gif|bmp)$#i';
$files = array();
if($handle = opendir($dirname)){
while(($file = readdir($handle)) !== false){
if(preg_match($pattern, $file)){
array_push($files, "<center><img src='" . $dirname . $file . "' alt='' /></br><br/><hr/></center>");
}
}
closedir($handle);
shuffle($files);
}
return implode("<center><br/>", array_slice($files, 0, $numimages)) . "<br/> </center>";
}
?>
<!-- <center><a id="myButton" href="#">MAS PICTURES!</a></center> -->
<center><input type='button' onClick='window.location.reload(true)' value='MAS PICTURES!!!' style="height:200px; width:150px" /></center>
<hr/>
<script type="text/javascript">
$(function() {
$("#myButton").click(function() {
$("#main").load("index.php");
});
});
</script>
<?php echo randomimages(); ?>
<center>Created by: Matt & Joe</center>
</div>
</body>
</html>
You can do the following:
Optimize the code by not reading the directory over and over. What you can do this by reading the directory once (and say then store the entries as an array in APC cache). Set a timeout for this APC key to bust the cache once in a while.
Call the `mt_rand` function with min as `0` and max as `count(array)-1` and access that index.
Generic code to read from directory can be as follows (needs modification to match your needs):
<?php
function &list_directory($dirpath) {
if (!is_dir($dirpath) || !is_readable($dirpath)) {
error_log(__FUNCTION__ . ": Argument should be a path to valid, readable directory (" . var_export($dirpath, true) . " provided)");
return null;
}
$paths = array();
$dir = realpath($dirpath);
$dh = opendir($dir);
while (false !== ($f = readdir($dh))) {
if (strpos("$f", '.') !== 0) { // Ignore ones starting with '.'
$paths[] = "$dir/$f";
}
}
closedir($dh);
return $paths;
}
Provide the directory full path to the variable $dirpath
$image_source_array=scandir($dirpath);
sort($image_source_array);
Use mt_rand function with min as 0 and max as count($image_source_array)-1 and access that index from the array to get the image name
and then access the image with the $dirpath/image name you will get the random image each time
Create function like this it will be the shortest approch
function randomimages() {
$dirname = isset($_REQUEST['dir']) ? $_REQUEST['dir'] : './photos/';
$image_source_array = scandir($dirname);
sort($image_source_array);
$image_count = count($image_source_array) - 1;
$rand_index = mt_rand(3, $image_count);
//Starting with 3 because scandir returns directory also in the 2 indexes like '.' and '..'
$rand_image_path = $dirname . $image_source_array[$rand_index];
return $rand_image_path;
}
For the sake of simplicity and reusability, you might want to use RegexIterator together with DirectoryIterator:
function randomimages($path, $num_images)
{
$images = array();
foreach (new RegexIterator(new DirectoryIterator($path),
'#\.(jpe?g|gif|png|bmp)$#i') as $file) {
$images[] = $file->getPathname();
}
shuffle($images);
return array_slice($images, 0, $num_images);
}
Using:
$path = isset($_REQUEST['dir']) ? $_REQUEST['dir'] : './photos/';
$num_images = isset($_REQUEST['num']) ? $_REQUEST['num'] : 1;
print implode('<br />', randomimages($path, $num_images));
I have this drupal slideshow which pulls images from a folder sequentially by image title (01_title.jpg, 02_title.jpg, etc..)
I was wondering if there is an easy way to randomize the images, so it starts with a different image every time you refresh the page?
you can view the slideshow here http://www.rubensteinpr.com/
Thanks!
<div id ="index">
<?php
// Note that !== did not exist until 4.0.0-RC2
$desired_extension = 'jpg'; //extension we're looking for
$banner_imgs_array = array(); // array of banner images
$banner_imgs = ''; // sting of banner images names comma dileneated
if ($handle = opendir(file_directory_path().'/banner_imgs')) {
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if(($file != ".") and ($file != "..")) {
$fileChunks = explode(".", $file);
if($fileChunks[1] == $desired_extension) //interested in second chunk only
{
$banner_imgs_array[] = $file;
}
}
}
closedir($handle);
$banner_imgs = implode(',', $banner_imgs_array);
}
?>
<div id="banner"><img src="<?php print file_directory_path(); ?>/temp_banner.jpg" width="702" height="310" border="0"></div>
<div id="bannerText">media relations • strategic planning • digital communications • crisis management</div>
<script type="text/javascript">
// <![CDATA[
var so = new SWFObject("<?php print file_directory_path(); ?>/banner.swf", "ban", "702", "310", "8", "#ffffff");
so.addParam('menu', 'false');
so.addParam("wmode", "transparent");
so.addParam("base", "<?php print file_directory_path(); ?>");
so.addVariable("banner_imgs", "<?php print $banner_imgs; ?>");
so.write("banner");
// ]]>
</script>
</div>
adding
shuffle($banner_imgs_array);
line just before
$banner_imgs = implode(',', $banner_imgs_array);
should do the trick.
array_rand will return one or more random array keys. If you want to shuffle the array itself, use shuffle.
Ok, so I'm loading a list of images by directory using PHP:
<?php
# fetch image details
$images = getImages("marc/img/livingrooms/");
# display on page
foreach($images as $img) {
echo "<li><img src=\"{$img['file']}\" title=\"\" alt=\"\"></li>\n";
}
?>
Then I'm using the Galleria JQuery plugin to style those items into a gallery:
$(document).ready(function(){
$('.dynolist').addClass('gallery_group'); // adds new class name to maintain degradability
$('ul.gallery_group').galleria({
history : true, // activates the history object for bookmarking, back-button etc.
clickNext : true, // helper for making the image clickable
insert : '#main_image', // the containing selector for our main image
onImage : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
// fade in the image & caption
image.css('display','none').fadeIn(1000);
caption.css('display','none').fadeIn(1000);
// fetch the thumbnail container
var _li = thumb.parents('li');
// fade out inactive thumbnail
_li.siblings().children('img.selected').fadeTo(500,0.3);
// fade in active thumbnail
thumb.fadeTo('fast',1).addClass('selected');
// add a title for the clickable image
image.attr('title','Next image >>');
},
onThumb : function(thumb) { // thumbnail effects goes here
// fetch the thumbnail container
var _li = thumb.parents('li');
// if thumbnail is active, fade all the way.
var _fadeTo = _li.is('.active') ? '1' : '0.3';
// fade in the thumbnail when finnished loading
thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
// hover effects
thumb.hover(
function() { thumb.fadeTo('fast',1); },
function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
)
}
});
});
The issue is that I need to give the first item pulled from that list a class of "active", so the first image will be loaded into the slideshow. Everything else works right now, other than getting that first image loaded.
Any suggestions?
$('selector:first').addClass('active');
Maybe?
Or what about
# display on page
$class = 'class="active" ';
foreach($images as $img) {
echo "<li><img ".$class."src=\"{$img['file']}\" title=\"\" alt=\"\"></li>\n";
$class="";
}
Try this:
# display on page
$counter = 0;
foreach($images as $img) {
if ($counter == 0) { // first
echo "<li class=\"active\"><img src=\"{$img['file']}\" title=\"\" alt=\"\"></li>\n";
}
else
{
echo "<li><img src=\"{$img['file']}\" title=\"\" alt=\"\"></li>\n";
}
$counter++;
}
If you want to do that on the PHP side, you could count, in your foreach loop, how many images have been displayed -- and if 0 have been displayed, add a class="active" to the one you are currently echoing.
For instance, something like this should do the trick :
$counter = 0;
foreach($images as $img) {
echo "<li><img src=\"{$img['file']}\" ";
if ($counter === 0) {
echo 'class="active"';
}
echo " title=\"\" alt=\"\"></li>\n";
$counter++;
}
The first time you'll loop, $counter will be 0, and class="active" will be echoed ; next times, it won't be 0 anymore, and no addtionnal active class will be added.
In jquery:
$(".gallery_group li:first-child").addClass("active");
In php:
# display on page
$first = true;
foreach($images as $img) {
echo "<li " . ($first ? "class='active'" : "") . "><img src=\"{$img['file']}\" title=\"\" alt=\"\"></li>\n";
$first = false;
}