如何从 PHP 中的文件目录中获取图像属性


How to Get Image Properties From File Directory in PHP

我使用以下代码在页面上的目录中显示图像

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

这工作正常,但我还需要访问要以alt=""显示的每个图像名称和以data-size=""显示的图像大小。你能告诉我如何使用getimagesize()getImageProperties()在这里吗?

要获取图像文件的尺寸,您需要将其path提供给 getimagesize(),要获取 altfilename,您可以使用 basename(),即:

$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;
}

getimagesize($filename) 返回 4 个元素的数组。第一个是宽度,第二个高度,第三个类型,第四个html属性(宽度="xxx"高度="xxx")

现在您可以像这样获取它们:

list($imageWidth,$imageHeight,$imageType,$imageAttributes) = getimagesize($image);