Brugebart PHP-script til billedegalleri

Dette forum bruges på EGET ANSVAR til at lege med scripts og andre ting med risiko for at beskadige sit eget og andres systemer.
Brugeravatar
NickyThomassen
Admin
Indlæg: 3650
Tilmeldt: 5. mar 2010, 19:58
IRC nickname: nicky
Geografisk sted: 192.168.20.42

Brugebart PHP-script til billedegalleri

Indlæg af NickyThomassen »

Jeg har længe kigget efter et script skrevet i PHP til at oprette et billedegalleri som "on the fly" generer den nødvendige kode ud fra billederne i en mappe, opretter thumbs til dem og slutter af med at generer den nødvendige HTML.

Det har jeg endelig fundet, og jeg tænkte at jeg ville dele. Scriptet er hentet her
http://webcheatsheet.com/php/create_thumbnail_images.php

Kode: Vælg alt

<?php
// script from http://webcheatsheet.com

// Relative path to script, e.g. $pathToImages = "pics/" and width of thumbs in pixels
function createThumbs( $pathToImages = "pics/", $pathToThumbs = "thumbs/", $thumbWidth = 100 )
{
  // open the directory
  $dir = opendir( $pathToImages );

  // loop through it, looking for any/all JPG files:
  while (false !== ($fname = readdir( $dir ))) {
    // parse path for the extension
    $info = pathinfo($pathToImages . $fname);
    // continue only if this is a JPEG image
    if ( strtolower($info['extension']) == 'jpg' )
    {
      echo "Creating thumbnail for {$fname} <br />";

      // load image and get image size
      $img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
      $width = imagesx( $img );
      $height = imagesy( $img );

      // calculate thumbnail size
      $new_width = $thumbWidth;
      $new_height = floor( $height * ( $thumbWidth / $width ) );

      // create a new temporary image
      $tmp_img = imagecreatetruecolor( $new_width, $new_height );

      // copy and resize old image into new image
      imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

      // save thumbnail into a file
      imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );
    }
  }
  // close the directory
  closedir( $dir );
}
// call createThumb function and pass to it as parameters the path
// to the directory that contains images, the path to the directory
// in which thumbnails will be placed and the thumbnail's width.
// We are assuming that the path will be a relative path working
// both in the filesystem, and through the web for links
createThumbs("pics/","thumbs/",250);
?>
(scriptet kan deles her efter behov)
<?php
function createGallery( $pathToImages = "pics/", $pathToThumbs = "thumbs/" )
{
  echo "Creating gallery.html <br />";

  $output = "<html>";
  $output .= "<head><title>Thumbnails</title></head>";
  $output .= "<body>";
  $output .= "<table cellspacing=\"0\" cellpadding=\"2\" width=\"500\">";
  $output .= "<tr>";

  // open the directory
  $dir = opendir( $pathToThumbs );

  $counter = 0;
  // loop through the directory
  while (false !== ($fname = readdir($dir)))
  {
    // strip the . and .. entries out
    if ($fname != '.' && $fname != '..')
    {
      $output .= "<td valign=\"middle\" align=\"center\"><a href=\"{$pathToImages}{$fname}\">";
      $output .= "<img src=\"{$pathToThumbs}{$fname}\" border=\"0\" />";
      $output .= "</a></td>";

      $counter += 1;
      if ( $counter % 4 == 0 ) { $output .= "</tr><tr>"; }
    }
  }
  // close the directory
  closedir( $dir );

  $output .= "</tr>";
  $output .= "</table>";
  $output .= "</body>";
  $output .= "</html>";

  // open the file
  $fhandle = fopen( "gallery.html", "w" );
  // write the contents of the $output variable to the file
  fwrite( $fhandle, $output );
  // close the file
  fclose( $fhandle );
}
// call createGallery function and pass to it as parameters the path
// to the directory that contains images and the path to the directory
// in which thumbnails will be placed. We are assuming that
// the path will be a relative path working
// both in the filesystem, and through the web for links
createGallery("pics/","thumbs/");
?>

Den eneste ulempe som jeg har fundet er, at scriptet ved hver kørsel opretter thumbs.
AJenbo
Admin
Indlæg: 20861
Tilmeldt: 15. nov 2009, 15:04
IRC nickname: AJenbo
Geografisk sted: Vanløse, København

Re: Brugebart PHP-script til billedegalleri

Indlæg af AJenbo »

Med henblik på dit tidligere emne om best practice har jeg rettet lidt i koden. Jeg har også gjort så den laver pænere thumbs.

Kode: Vælg alt

<?php
/**
 * Generate thumbnails and gallery for all jpg images in a directory
 *
 * PHP version 5
 *
 * @category Thumbnails
 * @package  Create_Thumbnail_Images
 * @author   Anders Jenbo <anders@jenbo.dk>
 * @license  Public domain http://en.wikipedia.org/wiki/Public_domain
 * @link     http://webcheatsheet.com/php/create_thumbnail_images.php
 */

$pathToImages = 'pics/',
$pathToThumbs = 'pics/thumbs/'
$thumbWidth = 250;
$generateHTML = true;

/**
 * Generate thumbnails for all jpg images in given folder
 *
 * @param string $pathToImages Relative path to pictures
 * @param string $pathToThumbs Relative path to store thumbnails in
 * @param int    $thumbWidth   Width of thumbs in pixels
 *
 * @return null
 */
function createThumbs($pathToImages, $pathToThumbs = 'thumbs/', $thumbWidth = 100)
{
    // open the directory
    $dir = opendir($pathToImages);

    // loop through it, looking for any/all JPG files:
    while (false !== ($fname = readdir($dir))) {
        // parse path for the extension
        $info = pathinfo($pathToImages . $fname);
        // continue only if this is a JPEG image
        //FIXME should probably use fifo to make sure it is the right mime
        if (mb_strtolower($info['extension']) == 'jpg') {
            echo "Creating thumbnail for $fname<br />\n";

            // load image and get image size
            $img = imagecreatefromjpeg($pathToImages . $fname);
            $width = imagesx($img);
            $height = imagesy($img);

            // calculate thumbnail size
            $new_width = $thumbWidth;
            $new_height = round($height * ($thumbWidth / $width));

            // create a new temporary image
            $tmp_img = imagecreatetruecolor($new_width, $new_height);

            // copy and resize old image into new image
            imagecopyresampled(
                $tmp_img,
                $img,
                0,
                0,
                0,
                0,
                $new_width,
                $new_height,
                $width,
                $height
            );

            // save thumbnail into a file
            imagejpeg($tmp_img, $pathToImages . $fname);
        }
    }
    // close the directory
    closedir($dir);
}

createThumbs($pathToImages, $pathToThumbs, $thumbWidth);

/**
 * Generate HTML gallery for images that has had thumbnails generated
 *
 * @param string $pathToImages Relative path to pictures
 * @param string $pathToThumbs Relative path to store thumbnails in
 *
 * @return null
 */
function createGallery($pathToImages, $pathToThumbs = 'thumbs/')
{
    echo "Creating gallery.html<br />\n";

    $output = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Thumbnails</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <style type="text/css">
    img {
        border: 0;
    }
    </style>
    </head>
    <body>
    <table cellspacing="0" cellpadding="2" width="500">
    <tr>';

    // open the directory
    $dir = opendir($pathToThumbs);

    $counter = 0;
    // loop through the directory
    while (false !== ($fname = readdir($dir))) {
        // Skip . and ..
        if ($fname != '.' && $fname != '..') {
            continue;
        }
        $output .= '<td valign="middle" align="center">
            <a href="' . $pathToImages . $fname '">
            <img src="' . $pathToThumbs . $fname . '" alt="' . $fname . '" />
            </a>
            </td>';

        $counter += 1;
        if ($counter % 4 == 0) {
            $output .= '</tr><tr>';
        }
    }
    // close the directory
    closedir($dir);

    $output .= '</tr></table></body></html>';

    // open the file
    $fhandle = fopen('gallery.html', 'w');
    // write the contents of the $output variable to the file
    fwrite($fhandle, $output);
    // close the file
    fclose($fhandle);
}

if ($generateHTML) {
    createGallery($pathToImages, $pathToThumbs);
}
Brugeravatar
NickyThomassen
Admin
Indlæg: 3650
Tilmeldt: 5. mar 2010, 19:58
IRC nickname: nicky
Geografisk sted: 192.168.20.42

Re: Brugebart PHP-script til billedegalleri

Indlæg af NickyThomassen »

Mange tak for opdateringen af koden, jeg er gået i gang med at opdatere siden ud fra den.

I første omgang fik jeg indsat css-koden i css-filen så scriptet bare skal kalde det, og så har jeg opdateret <table *** > til ren css med

Kode: Vælg alt

div.img {
margin         :2px;
height         :auto;
width         :100%;
float         :left;
text-align      :left;
}
div.img img {
display         :inline;
margin         :5px;
border         :1px solid #ffffff;
}

Så nu overholder siden html5 (igen). Næste del bliver så at opdatere ændringerne til thumbnail-delen :)