如何从php中的文件夹中仅拉出1张图片?

时间:2013-11-01 01:35:08

标签: php directory

我有工作代码,它从动态创建的文件夹中提取所有图像。但我想在显示页面中只显示特定文件夹中的1张图像。有什么建议? 我的代码:

<?php 
    $search_dir = "$directory/{$row['name']}{$row['hotel_address']}";
    $images = glob("$search_dir/*.jpg");
    sort($images);
    //display images
    foreach ($images as $img) {
        echo "<img src='$img' height='150' width='150' /> ";
    }

?>

2 个答案:

答案 0 :(得分:1)

您可以使用current从阵列中获取第一张图片。

<?php 
$search_dir = "$directory/{$row['name']}{$row['hotel_address']}";
$images = glob("$search_dir/*.jpg");
sort($images);
//display one image:
echo "<img src='current($images)' height='150' width='150' /> ";
?>

答案 1 :(得分:1)

您可以使用以下内容显示单个图像:

<?php 
    $search_dir = "$directory/{$row['name']}{$row['hotel_address']}";
    $images = glob("$search_dir/*.jpg");
    sort($images);

    // Image selection and display:

    //display first image
    if (count($images) > 0) { // make sure at least one image exists
        $img = $images[0]; // first image
        echo "<img src='$img' height='150' width='150' /> ";
    } else {
        // possibly display a placeholder image?
    }

?>

如果您想要随机图像,请执行以下操作:

    // Image selection and display:

    //display random image
    if (count($images) > 0) { // make sure at least one image exists

        // Get a random index in the array with rand(min, max) which is inclusive
        $randomImageIndex = rand(0, count($images)-1);
        $img = $images[$randomImageIndex]; // random image
        echo "<img src='$img' height='150' width='150' /> ";

    } else {
        // possibly display a placeholder image
    }