Behseini Behseini - 7 months ago 9
PHP Question

How to Get Image Properties From File Directory in PHP

I am using following code to display images in a directory on the page

$dirname = "img/data/new/";
$images = glob($dirname."*.png");
foreach($images as $image) {
echo '<img src="'.$image.'" alt="" data-size=""/><br />';
}


which is working fine but I also need to get access to each image name to be displayed in
alt=""
and image size in
data-size=""
. Can you please let me know how to use
getimagesize()
or
getImageProperties()
here?

Answer

To get the dimensions of an image file, you need to provide its path to getimagesize(), to get the filename for alt, you can use basename(), i.e.:

$dirname = "img/data/new/";
$website = "https://mysite/"
$images = glob($dirname."*.png");
foreach($images as $image) {
list($width, $height) = getimagesize($image); //get the $width, $height of the image
$filename = basename($image) // get the filename for alt
echo <<< LOL
<img src="{$website}{$dir}{$image}" alt="$filename" data-size="$width:$height"/><br />
LOL;
}
Comments