[PHP] Bilder-Karusell-Klasse

[PHP] Bilder-Karusell-Klasse

Eine einfache, leicht einzubindende Klasse, mit der man ein Bilder-Karusell bauen kann.

Carousel.php
PHP:
<?php
class CarouselException extends Exception{};

/**
* Image carousel class
*
* @author saftmeister
* @license BSD
*       
*/
class Carousel
{
  /**
   * The url which sends the image to the client
   *
   * @var string
   */
  private $imageUrl;

  /**
   * The url which displays the HTML for displaying the carousel
   *
   * @var string
   */
  private $indexUrl;

  /**
   * The directory which contains the image files
   *
   * @var string
   */
  private $directory;

  /**
   * Whether to use recursive search
   *
   * @var boolean
   */
  private $recursive;

  /**
   * The data holder
   *
   * @var array
   */
  private $allImages;

  /**
   * Maximum width (height will be aspected ratio)
   *
   * @var number
   */
  private $maxWidth;

  /**
   * Create a new carousel instance
   *
   * @param string $indexUrl        
   * @param string $imageUrl        
   * @param string $directory        
   * @param boolean $recursive        
   * @param number $maxWidth        
   * @throws CarouselException
   */
  public function __construct($indexUrl, $imageUrl, $directory, $recursive = true, $maxWidth = 0)
  {
    $this->indexUrl = $indexUrl;
    $this->imageUrl = $imageUrl;
    $this->directory = $directory;
    $this->recursive = boolval ( $recursive );
    $this->maxWidth = $maxWidth;
  
    if (! is_dir ( $directory ))
    {
      throw new CarouselException ( "Given path does not exist or is no directory!" );
    }
  
    clearstatcache ();
  
    $this->loadImageData ( $this->directory );
  }

  /**
   * Loads the images into data holder
   *
   * @throws CarouselException
   * @param string $path        
   */
  private function loadImageData($path)
  {
    if ($this->recursive)
    {
      $dir = new RecursiveDirectoryIterator ( $path );
      $iter = new RecursiveIteratorIterator ( $dir );
    }
    else
    {
      $iter = new DirectoryIterator ( $path );
    }
  
    $regex = new RegexIterator ( $iter, '/^.+\.jpg/i', RegexIterator::GET_MATCH );
  
    foreach ( $regex as $jpeg )
    {
      $key = md5 ( $jpeg [0] );
      $this->allImages [$key] = $jpeg [0];
    }
  
    if(!count($this->allImages))
    {
      throw new CarouselException("No images found!");
    }
  }

  /**
   * Retrieve the url to next image
   *
   * @return string
   */
  public function getNextLink()
  {
    $nextInArray = array_keys ( $this->allImages )[0];
    if (isset ( $_GET ['next'] ))
    {
      $id = $_GET ['next'];
      if (array_key_exists ( $id, $this->allImages ))
      {
        $found = false;
        foreach ( $this->allImages as $key => $value )
        {
          if ($found)
          {
            $nextInArray = $key;
            break;
          }
          if ($key === $id)
          {
            $found = true;
          }
        }
      }
    }
  
    return sprintf ( "%s?next=%s", $this->indexUrl, $nextInArray );
  }

  /**
   * Returns the url to the current image
   *
   * @return string
   */
  public function getCurrentLink()
  {
    return sprintf ( "%s?next=%s", $this->imageUrl, $this->getCurrentId () );
  }

  /**
   * Returns the current id
   *
   * @return string
   */
  public function getCurrentId()
  {
    $current = array_keys ( $this->allImages )[0];
    if (isset ( $_GET ['next'] ))
    {
      $id = $_GET ['next'];
      if (array_key_exists ( $id, $this->allImages ))
      {
        $current = $id;
      }
    }
  
    return $current;
  }

  /**
   * Returns the current image file path
   *
   * @throws CarouselException
   * @return string
   */
  private function getCurrentImageFile()
  {
    $id = $this->getCurrentId ();
  
    if (! $id)
    {
      throw new CarouselException ( "Image does not exist!" );
    }
  
    $image = $this->allImages [$id];
  
    return $image;
  }

  /**
   * Sends the current image to the client
   */
  public function getCurrentImage()
  {
    $image = $this->getCurrentImageFile ();
    $data = file_get_contents ( $image );
  
    $localDate = new DateTime ( 'UTC' );
    $localDate->setTimestamp ( filemtime ( $image ) );
  
    header ( 'Content-Type: image/jpeg' );
    header ( sprintf ( 'Content-Length: %d', strlen ( $data ) ) );
    header ( sprintf ( 'Last-Modified: %s', $localDate->format ( 'D, d M Y H:i:s \G\M\T' ) ) );
    header ( 'Cache-Control: public' );
    header ( sprintf ( 'ETag: "%s"', md5 ( $localDate->getTimestamp () . $image ) ) );
  
    echo $data;
    exit ();
  }

  /**
   * Retrieve the current image file height (respect the max width parameter)
   *
   * @throws CarouselException
   * @return number
   */
  public function getCurrentHeight()
  {
    $image = $this->getCurrentImageFile ();
    $info = getimagesize ( $image );
  
    if (! $info)
    {
      throw new CarouselException ( "Could not determine image size!" );
    }
  
    $height = $info [1];
    if ($this->maxWidth > 0 && $this->maxWidth < $info [0])
    {
      $ratio = $this->maxWidth / ($info [0] / 100) / 100;
      $height = $height * $ratio;
    }
    return $height;
  }

  /**
   * Retrieve the current image file width (respect the max width parameter)
   *
   * @throws CarouselException
   * @return number
   */
  public function getCurrentWidth()
  {
    $image = $this->getCurrentImageFile ();
    $info = getimagesize ( $image );
  
    if (! $info)
    {
      throw new CarouselException ( "Could not determine image size!" );
    }
  
    $width = $info [0];
    if ($this->maxWidth > 0 && $this->maxWidth < $info [0])
    {
      $width = $this->maxWidth;
    }
  
    return $width;
  }
}

Beispiel-Index index.php
PHP:
<?php
/**
* Example index file for the carousel
*
*/
require 'Carousel.php';
?>
<!DOCTYPE a PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>An image carousel class example</title>
  </head>
  <body>
  <?php
  try
  {
    $carousel = new Carousel('/ImageCarousel', '/ImageCarousel/image.php', 'd:/images', true, 200);
  
    printf('<a href="%s"><img width="%d" height="%d" src="%s"></a>', $carousel->getNextLink(),
        $carousel->getCurrentWidth(), $carousel->getCurrentHeight(), $carousel->getCurrentLink());
  }
  catch(Exception $ex)
  {
    echo $ex->getMessage();
  }
  ?>
  </body>
</html>

Beispiel-Bild-Sender image.php
PHP:
<?php
/**
* Example image displayer for the carousel
*/
require 'Carousel.php';

try
{
  $carousel = new Carousel('/ImageCarousel', '/ImageCarousel/image.php', 'd:/images');
  $carousel->getCurrentImage();
}
catch(Exception $ex)
{
  header("HTTP/1.1 404 File Not Found");
}

TODOs:
- Funktion einbauen, mit der man zurück gehen kann
- ErrorHandler.php und SimpleLogger.php für Fehlerlogging einbauen
Autor
saftmeister
Aufrufe
2.083
First release
Last update
Bewertung
0,00 Stern(e) 0 Bewertungen

More resources from saftmeister

Zurück