jueves, 12 de abril de 2012

Mostrar imagenes desde un directorio en formato 'jpg', 'jpeg', 'gif', 'png'

index.php

<html>
<head>
<title>Images</title>
</head>
<body>
<?php
require 'DirectoryItems.php';
$di =& new DirectoryItems('graphics');
$di->checkAllImages()or die('Not all files are images.');
$di->naturalCaseInsensitiveOrder();
//get portion of array
$filearray = $di->getFileArray();
echo "<div style=\"text-align:center;\">";
foreach ($filearray as $value){
    echo "<img src=\"graphics/$value\" /><br />file name: $value<br />\n";
}
echo "</div><br />";
?>
</body>
</html>

DirectoryItems.php

<?php
class DirectoryItems{
    //data members
    var $filearray = array();
////////////////////////////////////////////////////////////////////
//constructor
////////////////////////////////////////////////////////////////////
  function DirectoryItems($directory){
        $d = '';
      if(is_dir($directory))
        {
          $d = opendir($directory) or die("Couldn't open directory.");
          while(false !== ($f = readdir($d)))
            {
            if(is_file("$directory/$f"))
                {
                    $this->filearray[]=$f;
            }
          }
            closedir($d);
        }else{
            //error
            die('Must pass in a directory.');
        }
    }
////////////////////////////////////////////////////////////////////
//public functions
////////////////////////////////////////////////////////////////////
    function indexOrder(){
        sort($this->filearray);
    }
////////////////////////////////////////////////////////////////////
    function naturalCaseInsensitiveOrder(){
        natcasesort($this->filearray);
    }
////////////////////////////////////////////////////////////////////
    function checkAllImages(){
        $bln=true;
        $extension='';
        $types= array('jpg', 'jpeg', 'gif', 'png');
        foreach ($this->filearray as $value){
            $extension = substr($value,(strpos($value, ".")+1));
            $extension = strtolower($extension);
            if(!in_array($extension, $types)){
                $bln = false;
                break;
            }
        }
        return $bln;
    }
////////////////////////////////////////////////////////////////////
    function getCount() {
        return count($this->filearray);
    }
////////////////////////////////////////////////////////////////////
    function getFileArray(){
        return $this->filearray;
    }
}//end class
////////////////////////////////////////////////////////////////////
?>

No hay comentarios:

Publicar un comentario