我正在尝试显示已在视图中调整大小的所有图像。虽然目录中只有一个图像,但它只显示一个图像。这是我的代码:
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()));
}
任何帮助将不胜感激。
谢谢!
答案 0 :(得分:1)
为简洁起见;
在getFilesFromDir()
方法的内部循环中,您正在重置数组值,因为其键/索引不是唯一的。
而不是$holder[$finfo->getPath()] = $finfo->getFilename();
使用$holder[$finfo->getPath()][] = $finfo->getFilename();
来创建多维数组。
结果将是一个数组,其中第一个键包含路径,后跟一个文件数组。