如何用PHP批量获取一组图片的宽度和高度?
批量获取图片宽高的PHP实现方案
完全可行,下面给你一套可以直接用的批量处理代码,处理后能直接在浏览器复制结果,用完删掉代码即可:
<?php // 解除执行时间限制(处理大量图片时可选) set_time_limit(0); // 设置图片所在的服务器根目录绝对路径 $imageDir = $_SERVER['DOCUMENT_ROOT'] . "/path/to/your/images/"; // 允许处理的图片格式 $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp']; // 遍历目录下的所有文件 $files = scandir($imageDir); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>批量图片宽高结果</title> <style> table { border-collapse: collapse; width: 100%; margin: 20px 0; } th, td { border: 1px solid #ccc; padding: 10px; text-align: left; } th { background: #f5f5f5; } code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; } </style> </head> <body> <h2>批量图片宽高获取结果</h2> <table> <tr> <th>图片访问路径</th> <th>宽度(px)</th> <th>高度(px)</th> <th>生成的img标签</th> </tr> <?php foreach ($files as $file) { // 跳过目录标识 if ($file === '.' || $file === '..') continue; // 过滤非图片文件 $fileExt = strtolower(pathinfo($file, PATHINFO_EXTENSION)); if (!in_array($fileExt, $allowedExtensions)) continue; $fullServerPath = $imageDir . $file; $webAccessPath = "/path/to/your/images/" . $file; // 前端可访问的路径 // 获取图片尺寸 $sizeData = getimagesize($fullServerPath); if (!$sizeData) { echo "<tr><td>$webAccessPath</td><td colspan='3'>无法读取图片尺寸</td></tr>"; continue; } list($width, $height) = $sizeData; $generatedImgTag = "<img src='$webAccessPath' alt='' width='$width' height='$height' />"; ?> <tr> <td><?= $webAccessPath ?></td> <td><?= $width ?></td> <td><?= $height ?></td> <td><code><?= htmlspecialchars($generatedImgTag) ?></code></td> </tr> <?php } ?> </table> </body> </html>
使用说明
- 替换代码中的
/path/to/your/images/:两处路径都要改成你实际的图片目录(服务器根目录相对路径,确保前端能访问到) - 将这个PHP文件上传到服务器,访问该文件的URL
- 浏览器会生成带格式的表格,你可以直接复制需要的宽高数据,或者复制第三列的img标签代码
- 处理完成后,直接删除这个PHP文件即可
注意事项
- 确保服务器对目标图片目录有读取权限,否则无法获取图片尺寸
- 如果图片数量超过几百张,建议保留开头的
set_time_limit(0);,避免PHP执行超时 - 可以根据需求修改
$allowedExtensions数组,添加或移除支持的图片格式
内容的提问来源于stack exchange,提问作者pitzki
相关产品推荐
相关产品推荐

