显示 PHP 目录中的所有图像

Displaying all images in a directory with PHP

我试图在视图中显示所有已调整大小的图像。尽管目录中不止一张图像,但它只显示一张图像。这是我的代码:

namespace Application\Model;

class Images 
{
    /**
     * Gets the files from the specified directory
     * @return array
     */
    public static function getFilesFromDir()
    {
        $iterator = new \DirectoryIterator($_SERVER['DOCUMENT_ROOT'] . '/test_image/');

        $holder = array();

        foreach ($iterator as $finfo) {
            if ($finfo->isFile()) {
                $holder[$finfo->getPath()] = $finfo->getFilename();
            }
        }

        return $holder;
    }


    /**
     * Resizes images in a directory
     */
    public static function resizeImages() 
    {
        $percent = 0.5; // scales the image to half its original size


        foreach (self::getFilesFromDir() as $key => $value) {
            $img_size = getimagesize($key . '/' . $value);

            // get the original height and width of the image
            $o_width = $img_size[0];
            $o_height = $img_size[1];

            // set the new width
            $new_width = 500; // 500 pixels, can changed if need be

            if ($o_width != $new_width) {
                $new_height_calc = $new_width / $o_width;

                $new_height = $new_height_calc * $o_height;

                // now create the resized image
                $new_image = imagecreatetruecolor($new_width, $new_height);

                $image = imagecreatefromjpeg($key . '/' . $value);

                imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $o_width, $o_height);

                imagejpeg($new_image, $_SERVER['DOCUMENT_ROOT'] . '/test_image/resized_images/' . $value, 100);
            }
        }
    }

    /**
     * gets the resized images located in resized images directory
     * @return array
     */
    public static function getResizedImages()
    {
        $iterator = new \DirectoryIterator($_SERVER['DOCUMENT_ROOT'] . '/test_image/resized_images/');

        $holder = array();

        foreach ($iterator as $finfo) {
            if ($finfo->isFile()) {
                $holder[] = $finfo->getFilename();
            }
        }

        return $holder;
    }
}

在控制器中:

 public function indexAction()
 {
    Images::resizeImages();

    $images = function() {
        foreach (Images::getResizedImages() as $value) {
            $img[] = $value;
        }

        return array_values($img);
    };

    return new ViewModel(array('images' => $images()));
}

如有任何帮助,我们将不胜感激。

谢谢!

为简洁起见;

getFilesFromDir() 方法的内部循环,您正在重置数组值,因为它的 key/index 不是唯一的。 使用 $holder[$finfo->getPath()][] = $finfo->getFilename(); 而不是 $holder[$finfo->getPath()] = $finfo->getFilename(); 来创建多维数组。 结果将是一个数组,其中第一个键包含路径,后跟文件数组。