Displaying an image in php using two different variables? - php

I have my root folder, and within my root folder is a folder named images.
Within the images folder is 4 subfolders, each named after a Suit of cards.
Within each Suit folder, I have 13 pictures named after cards. Ace.jpg, Two.jpg, etc.
Within my Code, I declare each suit and card as a variable.
/*Array used to select a random number*/
$CardNumber = array();
$CardNumber[0]="Ace";
$CardNumber[1]="Two";
$CardNumber[2]="Three";
$CardNumber[3]="Four";
$CardNumber[4]="Five";
$CardNumber[5]="Six";
$CardNumber[6]="Seven";
$CardNumber[7]="Eight";
$CardNumber[8]="Nine";
$CardNumber[9]="Ten";
$CardNumber[10]="Jack";
$CardNumber[11]="Queen";
$CardNumber[12]="King";
/*Array used to select a random suit.*/
$CardSuit = array();
$CardSuit[0]="Clubs";
$CardSuit[1]="Diamonds";
$CardSuit[2]="Hearts";
$CardSuit[3]="Spades";
After a player picks a Card and a Suit, is there anyway to display the card he chose?
E.G. If You picked the 5 of Clubs, it would display the picture named Five.jpg from the Clubs folder?

As far as I understand you just need to create an image tag with the src pointing to the right file in the right directory...
$suit = 'Hearts';
$card = 'Queen';
printf('<img src="%s/%s.jpg">', $suit, $card);

I guess you could do the following if you want to pick a random card
$CNkey = array_rand($CardNumber);
$CSKey = array_rand($CardSuit);
$randomCardNumber = $CardNumber[$CNKey];
$randomCardSuit = $CardSuit[$CSKey];
$image = '/images/' . $randomCardSuit . '/' . $randomCardNumber . '.jpg'; // or any other image extensions
echo '<img src="' . $image . '">';

Related

I want to save file name as 1.jpg 2.jpg... 10.jpg

my problem is when I save image from line bot messenger they see each event and then work so I count number of file in directory(where I save image) and I want image name as
1.jpg
2.jpg
3.jpg
if($typeMessage=='image'){
$responseMedia = $bot->getMessageContent($idMessage);
$dataBinary = $responseMedia->getRawBody();
$files = scandir($botDataUserFolder);
$num_files = count($files)-2;
$filenamesave = $num_files.'.'.jpg;
file_put_contents($fileFullSavePath,$dataBinary);
}
please let me know what wrong with this code? I still save image as 0.jpg or 1.jpg and they overwrite on the old file
Problem with you code that you make count($files)-2;
But in php function "scandir" you will always receive back additionally dots directories(current dir and parent dir).
By first call count($files)-2 will return 0 and you system will create 0.jpg
Try this code, it will automatically skip dots using FilesystemIterator::SKIP_DOTS:
$save_path = "/tmp/dir_to_save";
$filesystem_iterator = new FilesystemIterator($save_path,
FilesystemIterator::SKIP_DOTS);
$number_of_files = iterator_count($filesystem_iterator);
$filename_save = ($number_of_files + 1) . '.jpg';
file_put_contents($save_path . DIRECTORY_SEPARATOR . $filename_save, "binary file data");
You will need to adapt it a little bit for you method, but it works correctly.

PHP' glob() to select images

In my case I have a folder with a lot of images. In my source I want to get all images of ONE product.
E.g the product ID (PID) is 12345, in my folder I have images like:
123456789.jpg
123.jpg
1234.png
12345.png
12345-1.jpg
123456-1.bmp
12345-2.gif
The images I want to select is:
12345.png
12345-1.jpg
12345-2.gif
All other images or not from that product.
At the moment I select them like:
glob("path/to/the/images/" . $product_id . "*.*", GLOB_BRACE);
problem is.. this also brings me images like:
123456789.jpg
123456-1.bmp
Is it possible to say: bring me all images that matches the PID followed by a DOT (.) and all images that matches the PID followed by a MINUS (-) ?
I am testing it here and of course in my source since a while but can't find a solution.
I think this is what you need:
glob("path/to/the/images/" . $product_id . "[.-]*", GLOB_BRACE);
You could do this as an if statement, like the below
if(glob("path/to/the/images/*" . $product_id . ".*", GLOB_BRACE)
OR glob("path/to/the/images/" . $product_id . "-*", GLOB_BRACE)) {
//DO Stuff
}

refresh / clear / redraw page with content from a different location

I've put together some code to search through a directory and for all the jpg images it finds, display thumbnails and my required iptc and exif info.
The problem is that I have many, many directories of photos and as it is I need an index.php file for each one.
My directories are named by month and year; "1401" for January 20014, "1402" for Feb etc. and I have a set of shortcut images for each one called "1401.jpg", "1402.jpg" etc.
so I use this code for users to nagivate to other directories where $shortcut has the values of 1401, 1402 etc:
echo("<img src=\"shortcutimages/" . $shortcut . "\">");
I'd love to allow users to navigate in a similar way without needing multiple index.php files.
I would guess the best way is as follows:
On a mouseclick on a link like above, the main php (similar to below) should be re-run, replacing what's currently displayed on the screen but with new value for $dir replaced with something like $dir="../" . $shortcut;
Is this the way to do it? As a newbie I apologise if this is really simple but as it is I can't seem to work it out.
thanks in advance for your help,
Sivadas
$dir="."; // or other folder path of choice!
$jpgcount=0;
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($image = readdir($dh)) !== false)
{
if (preg_match("/.jpg/", $image)) // only use .jpg files
{
$image=$dir . "/" . $image;
$exif = exif_read_data($image, 0, true);
$exif_name = $exif['FILE']['FileName'];
if(isset($exif['EXIF']['DateTimeOriginal']))
{
$timestamp = $exif['EXIF']['DateTimeOriginal'];
}
else
{
$timestamp = "1971:01:01 01:01:01"; // puts in a datestamp if one doesnt exist
}
$datename[] = $timestamp . $exif_name; // create array of date+name to allow sorting by date then retrieval of date ordered names once datestamp is removed
$jpgcount++; // counts number of jpgs in folder
}
}
sort($datename); // sort date+name array by date
for($c=0; $c<$jpgcount; $c++)
{
$image = pythonslice("$datename[$c]","19:"); // function strips off the datestamp (1st 19 characters) to leave the filename (taken from www.php.net/manual/en/function.substr.php slow at acedsl dot com)
$image=$dir . "/" . $image;
$size = getimagesize("$image", $info);
echo("<tr><td valign=top> <IMG border=0 src=showthumb.php?image=" . str_replace(' ', '%20', $image) ."><td><td valign=top><font size=-1 face=\"Arial Narrow\">"); // get thumbnail and link to full image
show_metadata($image,$info); // function to display all required metadata
echo "</font></td></tr>";
}
closedir($dh);
}
}

PHP syntax equivalent to SQL %

I have a folder unit_images that is full of images with random names except they have a prefix that corresponds to a PRIMARY KEY in a db table.
1_4534534fw4.jpg
2_43534tw4t45.png
You get my point. I am using YoxView to view images and am doing something like this:
<?php
$query = "SELECT id FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '<div class="yoxview">';
while ($row = mysqli_fetch_assoc($result))
{
echo '<img src="unit_images/01.jpg" alt="First" title="First image" />
<img src="unit_images/02.jpg" alt="Second" title="Second image" />'
}
echo '</div>';
?>
I want to list the images from my folder unit_images WHERE the unit is the one currently being shown.I just do not know how to tell PHP the filename. I want to do something similar to a 1_% in SQL. Does that make sense? Since I do not know what the rest of the filename looks like I just need to tell php it doesn't matter.
The closest equivalent to SQL's % wildcard that works for files is the shell's * wildcard, which is available in php through the glob() function. You can iterate through its results as follows:
foreach (glob("unit_images/1_*.jpg") as $filename) {
echo '<img src="unit_images/' . htmlspecialchars(basename($filename))
. '" />';
}
If I understand you correctly, you want to get a list of items in a directory with a certain prefix.
Step 1 (use sandir() to determine the items in the directory):
$files = scandir('unit_images');
Step 2 (eliminate the unwanted image names):
for ($i=0; $i<count($files); i++)
{
$file = $files[i];
$prefix = explode("_", $file)[0];
if ($prefix != $_GET['id'])
{
unset($files[i]);
}
}
$files is now an array of only the file names prefixed with $_GET['id]
My advice would be to store the whole name of the file in a column so that you can reference it directly instead of having to search in the file system for a matching name.
Having said that, you can search for a file using the glob PHP function.
Maybe you can do something like this:
glob("unit_images/<YOUR_PRIMARY_KEY>_*.{png,jpg}", GLOB_BRACE);

Selecting random photos from featured album, PHP

Greetings,
I am adding four random photos from a featured photo album to the front page of a site in the form of a jQuery photo slider. Since all of the images must be the same size, I select only horizontal photos, shuffle them, and then trim that down to 4. Here is the code I am using. My question - is there a simpler, perhaps more efficient way to do this? Or is my method fairly sound?
Thanks!
$getImages = $gallery_db->query("SELECT * FROM images WHERE album = '5'"); //sample SQL
$imagesArr = array();
while ($image = $getImages->fetch()) {
$path = "http://somewhere.com/gallery/photos/" .
$image['album'] . "/" . $image['filename'] . ".jpg"; //All files are .jpg
list ($width, $height) = getimagesize($path);
if ($width > $height) {
$imagesArr[] = $path;
}
}
shuffle($imagesArr);
array_splice($imagesArr, 4)
and then, to output:
foreach ($imagesArr as $path) {
echo "<img src=\"$path\" width=\"220\" height=\"110\"/><br/>\n";
}
Your solution looks just fine, it's pretty simple and straight forward. But remember, premature optimization is the root of all evil :)
A improvement would be to store the dimensions of each image in your database, so that you can fetch all images of a certain size and just take 4 random images.

Categories