My PHP knowledge is kind of limited, and I was trying to search for different PHP/JavaScript solutions, but nothing helped me to make it work, so I'd just try to ask the question directly.
I have the following PHP code that loads all the images from a specific folder on server:
foreach(glob($images_path . '*.*') as $filename){
echo '<img src="' . $filename . '" class="preview" />';
}
Now, in order to give different styles to the images, based on their kind, I want to recognize the extension of the file, whether with JavaScript/jQuery or PHP, and to put it as a class (preferably, but could be some other idea)... let's say, after the class "preview" which I already have in the code. It could be similar to the extension, just without the dot, of course; e.g. class="preview png".
Thank you very much in advance!
foreach(glob($images_path . '*.*') as $filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
echo '<img src="' . $filename . '" class="preview ' . $ext . '" />';
}
try with this.
foreach(glob($images_path . '*.*') as $filename){
$extension = str_replace('.', '', strrchr($filename, '.'));
echo '<img src="' . $filename . '" class="preview '. $extension .'" />';
}
Related
Below are coding that I currently use to display images from database :
$con = mysqli_connect('localhost','root','','demo') or die('Unable To connect');
$query = mysqli_query($con,"SELECT * FROM images");
while($row=mysqli_fetch_assoc($query))
{
echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />';
}
Problem with those coding : It only display images with .png extension because I am using echo '<img src="data:image/png;base64,' . base64_encode($row['image']) . '" />'; to display it.
What I am trying to do : I wanted to display images with extension .jpeg .png and .gif as well.
Is there anybody that can help me with other simple way of displaying images? Thank you.
Store the format in the database as well:
$con = mysqli_connect('localhost','root','','demo') or die('Unable To connect');
$query = mysqli_query($con,"SELECT * FROM images");
while($row=mysqli_fetch_assoc($query))
{
echo '<img src="data:image/' . $row['format'] . ';base64,' . base64_encode($row['image']) . '" />';
}
Hi Just get the image extension and use it
$ext = pathinfo($row['image'], PATHINFO_EXTENSION);
echo '<img src="data:image/' . $ext . ';base64,' . base64_encode($row['image']) . '" />';
#FrankerZ already gave correct solution but if you have already stored base64 images on your database it will be problematic to add format column.
You can discover the mime type of image from base64 like that;
$img = $row['image']; // base64 of your image
$fileInfo = finfo_open(); // file info resource
$mimeType = finfo_buffer($fileInfo, $img, FILEINFO_MIME_TYPE);
If you have already existing records, do not apply this methodology on your each iteration. Simply add new column to your database, and fill/update these new colums using this methodology. After that, use #FrankerZ 's solution.
I'm not sure exactly where this script will be running, so it must be able to access this directory from anywhere.
I'm trying to create a list of images by getting the image file names from a directory, filtering them until I only have the image formats I want, then displaying them using an <img> tag.
The first bit went really well. Outputting the HTML is proving to be a problem.
While I can use $_SERVER["DOCUMENT_ROOT"] to work with the directories in PHP, it's problematic to output that value as part of the path in thetag'ssrc` attribute.
Here is my current code:
$unkwown_files = scandir($_SERVER['DOCUMENT_ROOT'] . "/path/images");
foreach($unkwown_files as $file) {
$exploded_filename = explode(".", $file);
$file_type = array_pop($exploded_filename);
$accepted_filetypes = [
"png",
"jpg",
"gif",
"jpeg"
];
$picture_names = [];
if (in_array($file_type, $accepted_filetypes)) {
$picture_names[] = $file;
}
}
foreach($picture_names as $picture) {
$path_to_image = $_SERVER['DOCUMENT_ROOT'] . "/nodes/images" . $picture;
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
A slightly different approach for you that filters files by extension from the outset.
$dir = $_SERVER['DOCUMENT_ROOT'] . "/path/images/";
/*
glob() searches for files/paths that match the pattern in braces and returns the results
as an array.
The '*' is a wildcard character as you would expect.
The flag 'GLOB_BRACE' expands the string so that it tries to match each
( From the manual: GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c' )
*/
$col = glob( $dir . "*.{jpg,png,gif,jpeg}", GLOB_BRACE );
/*
Iterate through the results, with each one being the filepath to the file found.
As the glob() function searched for the required types we don't need to check
if they are in the allowed types array.
Because you do not wish to display the fullpath to the image, a relative path is
preferred - thus we remove, from the path, the document root.
*/
foreach( $col as $index => $file ){
$path_to_image = str_replace( $_SERVER['DOCUMENT_ROOT'], '', $file );
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
Try this out
foreach($picture_names as $picture) {
$path_to_image = $_SERVER['DOCUMENT_ROOT'] . "/nodes/images/" . $picture;
echo '<img src="' . $path_to_image . '" class="upload_thumbnail"/>';
}
Image is stored in database (as varchar(255)), but on page isn't shown.
This is code that stored image, and put's image in folder:
if (isset($_FILES["image"])) {
$title = date("dmyHms") . "_" . $_FILES["image"]["name"];
$path = "img/profile/" . $_POST["id"] . "_" . $title;
move_uploaded_file($_FILES["image"]["tmp_name"], $path);
}
And this is to display image:
foreach ($conn->results() as $conn):
$img = $_SERVER["CONTEXT_DOCUMENT_ROOT"] . $path . "img/profile" . $conn->id . "_" . $conn->image;
if (file_exists($img)) {
$image = $path . "img/profile/" . $conn->id . "_" . $conn->image;
} else {
$image = $path . "img/noimage.png";
}
<?php endforeach; ?>
When I print_r $img, it shows right path to image and still image is not displayed.
Display:
<?php echo $image; ?>
Where did you echoing your image? If it is inside foreach, you need to change your code little bit...
$image = '<img src="'.$path . "img/profile/" . $conn->id . "_" . $conn->image . '" />';
Hope, will work perfectly for you.... TQ
The following line is not correct:
foreach ($conn->results() as $conn):
Don't overwrite $conn. Change the variable to something different like $result
I want to be able to present the photo of a user. That user may be of the type Doctor, Nurse or Patient and each person belonging to each of those types has a distinct ID which identifies him. I have the photos of each type of users separated in three folders inside the directory /images/user_upload/ and a given user may or may not have a photo. If he has a photo, I want to present the photo with a name which is the same as his ID (Note that I don't know the extension of this file, only the name). If he doesn't I want to present a default image. I have a function called printUserPhoto for this end.
function printUserPhoto()
{
$path = '/images/user_upload/' .ucfirst($_SESSION['listtype']). '/' .$_SESSION['id']. '.*';
$source = glob($path);
if(empty($source))
echo '<img src="images/default_profile_img.png" />';
else
echo '<img src="',$source[0],'" />';
}
Although, I always get an empty array in the variable $source, even though the image exists. What am I doing wrong?
This way with glob
function printUserPhoto()
{
$pathToDocumentRoot = $_SERVER['DOCUMENT_ROOT'];
$path = $pathToDocumentRoot . '/images/user_upload/' .ucfirst($_SESSION['listtype']). '/' .$_SESSION['id']. '.*';
$source = glob($path);
if(empty($source)){
echo '<img src="images/default_profile_img.png" />';
} else {
echo '<img src="',$source[0],'" />';
}
}
Maybe limit the filetypes user can upload. With that you could do something like this:
function printUserPhoto()
{
$pathToDocumentRoot = $_SERVER['DOCUMENT_ROOT'];
$path = $pathToDocumentRoot . '/images/user_upload/' .ucfirst($_SESSION['listtype']). '/' .$_SESSION['id'];
$file = "images/default_profile_img.png";
if(file_exists($path . '.jpg')){
$file = $path . '.jpg';
}else if(file_exists($path . '.png')){
$file = $path . '.png';
}else if(file_exists($path . '.gif')){
$file = $path . '.gif';
}
echo '<img src="' . $file . '" />';
}
Also as being said by #Phil you are now referring to the file system root / being absolute path not relative to your document root.
I need to build a dynamic image gallery plugin for Joomla! that will go into a specific folder and pull out all images from the folder and show first of them as a large preview image and the rest in a list. Afterwards I will need to make the preview image open in a lightbox if clicked and in the lightbox I need to have the small thumbnails of listed images as well.
But know I need just php to go to the folder and pull out all the images from the folder specified. I have googled a bit and found some solution but this does not work for some reason I don't understand. Could someone tell me please, what is wrong with the code?
Thanks!
<div id="images">
<?php
$images_dir = 'images/';
$scan = scandir($images_dir);
echo '<img src="' . $images_dir . $scan[2] . '"alt="image" />';
?>
<ul id="smallimages">
<?php
for($i=0; $i<count($scan); $i++){
$ext = substr($scan[$i], strpos($scan[$i], '.'), strlen($scan[$i]-1));
$filetypes = array('.jpg', '.JPEG', '.jpeg');
if(in_array($ext, $filetypes)){
echo '<li><img src="' . $images_dir . $scan[$i] . '" alt="' . $scan[$i] . '"></li>';} }?></ul>
</div>
I think it's because you haven't defined the path correctly. Try using the following:
$images_dir = JUri::root() . 'plugins/content/plg_new/images';
JUri::root() is the root of your Joomla site so change the path from there on accordingly to where ever your images are located
Hope this helps
Does this work for you?
<?php
$image_directory="hrevert/images/";
$pictures = glob("$image_directory*.{gif,jpg,png}", GLOB_BRACE);
//displays the first image
$first_img=reset($pictures);
echo "<img src=\"".$first_img."\" width='20px' />";
//loops through other images and prints them
echo "<ul>";
foreach($pictures as $picture) {
echo "<a href='$picture'><img src=\"".$picture."\" width='20px' /></a>";
}
echo "</ul>"
?>