PHP Получить размеры изображений в директории - PullRequest
1 голос
/ 21 марта 2012

У меня огромное количество фотографий, которые нужно отсортировать.Мне нужно знать размеры каждой фотографии, чтобы узнать, или она требует изменения размера.Как программист, я убежден, что должен быть более быстрый способ сделать это.

Я получил довольно далеко.Следующий код читает директорию и все субдиректории.Но в тот момент, когда я пытаюсь извлечь размеры, цикл останавливается на 8% всех изображений, которые необходимо проверить.Может быть, PHP не разрешает делать больше вычислений?Что происходит!?

Вот как далеко я ушел:

checkDir('dir2Check');</p> <pre><code>function checkDir($dir, $level = 0) { if ($handle = opendir($dir)) { while (false !== ($entry = readdir($handle))) { if (!preg_match('/\./i', $entry)) { echo echoEntry("DIR\\", $entry, $level); checkDir($dir.'/'.$entry, $level+1); } else { if ($entry != "." && $entry != ".." && $entry != ".DS_Store") { // if I comment the next line. It loops through all the files in the directory checkFile($entry, $dir.'/'.$entry, $level); // this line echoes so I can check or it really read all the files in case I comment the proceeding line //echo echoEntry("FILE", $entry, $level); } } } $level--; closedir($handle); }

}

// Checks the file type and lets me know what is happening
function checkFile($fileName, $fullPath, $level) {
if (preg_match('/\.gif$/i', $fullPath)) {
    $info = getImgInfo(imagecreatefromgif($fullPath));
} else if (preg_match('/\.png$/i', $fullPath)) {
    $info = getImgInfo(imagecreatefrompng($fullPath));
} else if (preg_match('/\.jpe?g$/i', $fullPath)){ 
    $info = getImgInfo(imagecreatefromjpeg($fullPath));
} else { 
    echo "XXX____file is not an image [$fileName]<br />";
}

if ($info) {
    echo echoEntry("FILE", $fileName, $level, $info);
}

}

// get's the info I need from the image and frees up the cache
function getImgInfo($srcImg) {
$width = imagesx($srcImg);
$height = imagesy($srcImg);
$info = "Dimensions:".$width."X".$height;

imagedestroy($srcImg);
return $info;

}

// this file formats the findings of my dir-reader in a readable way
function echoEntry($type, $entry, $level, $info = false) {
$output = $type;

$i = -1;
while ($i < $level) {
    $output .= "____";
    $i++;
}

$output .= $entry;

if ($info) {
    $output .= "IMG_INFO[".$info."]";
}

return $output."<br />";

}

Ответы [ 2 ]

3 голосов
/ 21 марта 2012

Следующее похоже на то, что вы делаете, только оно использует php's DirectoryIterator, который, по моему скромному мнению, чище и более ООП-у

<?php

function walkDir($path = null) {
    if(empty($path)) {
        $d = new DirectoryIterator(dirname(__FILE__));
    } else {
        $d = new DirectoryIterator($path);
    }

    foreach($d as $f) {
        if(
            $f->isFile() && 
            preg_match("/(\.gif|\.png|\.jpe?g)$/", $f->getFilename())
        ) {
            list($w, $h) = getimagesize($f->getPathname());
            echo $f->getFilename() . " Dimensions: " . $w . ' ' . $h . "\n";
        } elseif($f->isDir() && $f->getFilename() != '.' && $f->getFilename() != '..') {
            walkDir($f->getPathname());
        }
    }
}

walkDir();
1 голос
/ 21 марта 2012

Вы можете просто использовать getimagesize ()

  list($width, $height) = getimagesize($imgFile);
...