Display random images from folder with PHP without duplicates - php

I am trying to display a certain amount of random images from one directory on my website without displaying duplicates.
I found this question: Display 2 random pictures PHP with no duplicates which partially answers my problem:
<?php
$pics = array('image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg');
$images = array_rand($pics, 2);
?>
<img src="images/<?php echo $pics[$images[0]]; ?>" />
<img src="images/<?php echo $pics[$images[1]]; ?>" />
The problem I have is that the images are uploaded to the folder with completely different/random names such as 1a2265fg65444.jpg 55v4423097ww6.jpg etc, so I can't manually add them to the $pics array. I need to somehow scrape the directory for *.jpg and have the array generated automatically
I did try Michal Robinsons answer on Show Random images from a folder without repeating using JS or PHP but couldn't get it to print anything for some reason:
$all_images = glob("/images/photos/{*.jpg}", GLOB_BRACE);
shuffle($all_images);
$images = array();
foreach ($all_images as $index => $image) {
if ($index == 15) break; // Only print 15 images
$image_name = basename($image);
echo "<img src='/images/photos/{$image_name}' />";
}
Perhaps I'm missing something?
Any pointers would be simply awesome.
Many thanks

try this
$scan = scandir("/images/photos/");
shuffle($scan);
$r = rand(2, count($scan)); // maybe (count($scan) - 1)
printf("<img src='/images/photos/%s' />", basename($scan[$r]));

Thanks Aron, but I managed to fix it by changing:
glob("/images/photos/ to
glob("images/photos/
To complicate things further though, I just realized I need to show 1 image from a 1st folder followed by another image from a 2nd folder, and repeat this about 5 times, still without showing any duplicate :/ This is as far as I have got, but seem to be digging a bigger hole that doesn't work, as I'm stuck at the foreach...:
$all_images1 = glob("images/photos/{*.jpg}", GLOB_BRACE);
$all_images2 = glob("images/photos1/{*.jpg}", GLOB_BRACE);
shuffle($all_images1);
shuffle($all_images2);
$images1 = array();
$images2 = array();
$class = 1;
foreach ($all_images1 as $index1 => $image1) {
if ($index1 == 10) break; // Only print 15 images
$image_name1 = basename($image1);
echo "<img src='/images/photos/{$image_name1}' class='image".$class++."' /> <img src='/images/photos1/{$image_name2}' class='image".$class++."' />";
}
Am I going in the wrong direction to do this?
Thanks Ted

Related

Echo values from two foreach arrays without duplicates

I have this two arrays:
$files=glob("filepath/folder/*.*);
$thumbs=glob("filepath/folder/thumbs/*.*);
Main folder called in $files gets the full resolution images, while thumb has thumbnails for faster page loading, so it does not need to load the big images and resize them.
But my problem is now how to echo these two loops out?
I've tried nested foreach loops like
foreach ($files as $fl){
foreach ($thumbs as $tb) {
echo '<img src="<?=$tb?>">';
}
}
But this makes duplicates because it echoes for each element in files and for each in thumbs.
How can I echo them without duplicating?
Thanks everyone for help, this worked
$len = max(count($files), count($thumbs));
for($i=0; $i<$len; $i++){
$fl = isset($files[$i]) ? $files[$i] : '';
$tb = isset($thumbs[$i]) ? $thumbs[$i] : '';
echo <img src="<?=$tb?>">;
}

How would I link to thumbnails in a subdirectory, when using php to get a list of images?

I'm sorry if the title is a little vague ... I'm still relatively new at PHP (3 months or so) Also, my native tongue is not English, so please bear with me :) I have also searched this site and google extensively to try and find a solution, but without any luck.
I have a script set up in my images directory that scans all the subdirectories, and then outputs a list of links that, if clicked, will take you to a page, where all the images of the selected subdirectory are displayed. The path to such a page would be:
www.mysite.com/images/list_images.php?folderName=RandomFolder
The code for this:
images/index.php
<?php
$path = 'images/' ;
$results = scandir($path);
for ($i=0;$i<count($results);$i++)
{
$result=$results[$i];
if ($result === '.' or $result === '..')
continue;
if (is_dir($path . '/' . $result))
{
echo "<a href='list_images.php?folderName=$result'>$result</a><br/>";
}
}
?>
--------------------
list_images.php
<?php
if(isset($_GET['folderName']))
$folder=$_GET['folderName'];
$path = 'images/'.$folder.'/' ;
$images = glob($path . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach ($images as $image)
{
echo "<a href='$image'><img src='$image'/></a>";
}
?>
Now, my question:
In each of my image subdirectories I have another subdirectory called 'thumbs', that contains - yes, you guessed it - thumbnails. Each thumbnail is named exactly the same as its corresponding file in the directory above it. Now, how would I make the img src in the above code to point to the thumb?
Any help would be very welcome! Thank you in advance!
EDIT:
I looked over my code again, and I made few extra lines. It still doesn't work, but at least it now outputs thumbnails, which links to the larger image. Here's the new code:
list_images.php
if (isset($_GET['folderName'])) $folder=$_GET['folderName'];
$path = 'images/'.$folder.'/' ;
$thumb_path = ''.$path.'/thumbs/';
$thumbs = glob($thumb_path . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$images = glob($path . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach ($thumbs as $thumb){
foreach ($images as $image){
echo "<a class='fancybox' href='$image'><img src='$thumb'/></a>";
}
}
It kinda works now. The only problem is, that it outputs 13 identical thumbnails to each picture - and it does it 13 times (for a directory containing 13 image files) so there is 169 thumbnails in total.
Any ideas how to fix this?
If you are sure that the folder name is thumbs, there is no reason you can't hardcode this. Take a look at the following.
echo "<a href='$image'><img src='thumbs/$image'/></a>";
You could do a str_replace on the path.
If the path to the image is mydir\image01\pic01.jpg
str_replace('image01','image01\thumb',$image);
would point to mydir\image01\thumb\pic01.jpg

PHP - Glob multiple file extensions only displays first extension listed

I have both jpg and gif images in my directory and I am trying to display them both.
However, below will only display gif:
$pictures = glob("images/*.{gif,jpg}", GLOB_BRACE);
And this below will only display jpg:
$pictures = glob("images/*.{jpg,gif}", GLOB_BRACE);
Here is the whole thing I am working with:
<?php
$pictures = glob("images/*.{gif,jpg}", GLOB_BRACE);
for( $i=0; $i<=10; $i++ ){
echo "<img src=\"".$pictures[$i]."\" />";
}
?>
I have also tried with an absolute path and had no such luck displaying both.
What might be the problem?
Thanks in advance.
You seem to be limiting your search to the first 10 matches. If there are more than ten of each, then you will get them in the order you specified (since they are sorted by how they are found, not alphabetically).
You could use a foreach loop to iterate through all files, or you could add sort($pictures) before the loop.

php web image search

I want to do a picture search engine. I use simple_html_dom and preg_match_all to get all the images, then use getimagesize to get all the image sizes.
Here is one part of my code.
<?php
header('Content-type:text/html; charset=utf-8');
require_once 'simple_html_dom.php';
$v = 'http://www.jqueryimage.com/';
$html = file_get_html($v);
foreach($html->find('img') as $element) {
if( preg_match('#^http:\/\/(.*)\.(jpg|gif|png)$#i',$element->src)){
$image = $element->src;
//$arr = getimagesize($image); //get image width and height
//$imagesize = $arr[0] * $arr[1];
echo $image.'<hr />';
}
}
?>
First question, how to add a judgement so that I can echo the biggest size image? (only one image).
Second question, I can get the image real url in these two possibilities, first where image is as a 'http' began, second where image is as a / began.
But how to get the image real url in the situation where image is as a './' or ../ or ../../ began? it is difficulty for me to judge how many ../ in a image, then cut the site url to complement a image real url?
Thanks.
Insert this before foreach loop:
$maxsize = -1;
$the_biggest_image = false;
Insert this below $image = $element->src; line
$arr = getimagesize($image);
if (($arr[0] * $arr[1]) > $maxsize) {
$maxsize = $arr[0] * $arr[1];
$the_biggest_image = $image;
}
After foreach loop you'll have $the_biggest_image variable set or false if nothing found. This will take first one if more than one 'biggest image' found.
For second question, I don't know!
Edit: fixed something!

display random images without repetition

My name is Shruti.I'm new to php. I have a program which displays images randomly, there are about 200 images in my program.I want to display the random images with out repetition, can any one please help with this. here is my code.
Appreciate your help
Thank you.
I don't know whats about the $img_id but you could consider to use shuffle().
shuffle($file_array);
But then you loose the connection to $img_id. You could (I am not sure if this is the best solution), build your array this way:
$file_array = array(
array("images/bag200.bmp", 1),
array("images/bag178.bmp", 1),
array("images/bag004.bmp", 0,
...
);
In the long run, it is probably better to store all the image paths in a CSV file or even a database. Believe me, you don't want to maintain an array with > 200 entries manually ;)
You can loop over images this way (they are in random order now):
<?php foreach($file_array as $image): ?>
<img src="<?php echo $image ?>" />
<?php endforeach; ?>
If you only want to display a subset of the images, randomly chosen, you can do this:
$n = 20; // want to display 20 images
$rand = array_rand(range(0,200), $n); // draw keys randomly
shuffle($rand); //shuffle keys
foreach($rand as $r) {
echo '<img src="' . $file_array[$r] . '" />';
}
Some comments on your code:
$ran = array_rand($file_array);
$ran contains a key randomly chosen from the images.
for ($i=0;$i<200;$i++) {
//while (in_array($tst,$rand_array)){
$tst = $file_array[$ran];
$id = $img_id[$ran];//}
$rand_array[] = $tst;
$rand_id[] = $id;
}
You always pick the same entry from $file_array and $image_id because you never change $ran. That is way you get the same image 200 times.
If you want randomness but require uniqueness, you are looking for a quasi-random number generator. There are many different types with different properties. Look here for information on creating an algorithm: http://www.mathworks.nl/access/helpdesk/help/toolbox/stats/br5k9hi-8.html

Categories