2

我有大量的照片需要整理。我需要知道每张照片的尺寸才能知道,否则需要重新调整大小。作为一名程序员,我相信必须有一种更快的方法来做到这一点。

我走得很远。以下代码读取目录和所有子目录。但是,当我尝试提取尺寸时,循环在需要检查的所有图片的 8% 处停止。难道是PHP不允许做更多的计算?到底是怎么回事!?

这是我走了多远:

checkDir('dir2Check');

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 />";

}

4

2 回答 2

4

以下内容与您所做的类似,只是它使用了 php 的 DirectoryIterator,在我看来它更干净,更 OOP-y

<?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();
于 2012-03-21T18:03:01.423 回答
1

您可以简单地使用getimagesize()

  list($width, $height) = getimagesize($imgFile);
于 2012-03-21T17:47:06.737 回答