Page 1 of 1

simple image gallery>>>>

Posted: Fri Mar 10, 2006 11:52 am
by modplod
hi all, over the last two weeks i've been working on my first OOP script, I finnished the first phase, and thourght it was worth posting, even just to find ways to improve the code..

This class reads a directory structure, creates thumbs and displays them in a table with links to view a lager version of the file.

Please be burtal and let me know how I can improve this class, and fee free to use the cde as you need, this class works fine, but needs afew rough edges taken off


gallery.class.php

Code: Select all

<?	
# Gallery class 0.9.5/3.2006

# DEBUG VERSION, NOT FOR RELEASE
# PLEASE DO NOT USE THIS CODE IN ANY PRODUNCTION SCRIPTS.
# THIS CODE HAS NOT BEEN TESTED AND MAY BE UNSTABLE

# gallery . class for php 5+ by leigh edwards Feb 28 2006
# Please send any information on any problems you encounter to
# leighjedwards@msn.com
class gallery{



	# How to use this class
	#
	# This class requiers thumbnail.class.php
	#
	# Simply create your html page to hold your gallery and insert the method calls as needed:
	# The easyest way is to place an include satment in your file and just included the packedged gallery.php file
	# include("classes/gallery/gallery.php");
	# example of gallery.php

	# once you hace your page created, make a directory in you www rot folder to hold your galleries
	# Place folders containing your image files within this folder.
	#
	# Next edit the config settings in this file and your all set.

	# Known Bugs
	# Thumbs: If you list the dir in windows exploror a thumbs file may be created, this can sometimes (in larger folders)
	# be listed giving a blank space in the gallery, to fix simply remove the thumbs file from the dir (may be hidden)
	#
	# Menu: The listing for the menu will list files as well, so be carfull not to place any files in the gallery root
	#
	# Menu: Folder holding images should not use spaces in there names, as this can 'somtimes' cause the class to
	# list them incorrecly in the menu, This is server dependant and does work on most server, however if you find
	# some of your images or directories are not being listed, you should check this first.
	#
	# Also if a file or dir that is not included in the extensions arrar is found in the gallery folder it may be listed
	# along with the other (correct) files, but displayed as a blank scpace in the thumbnail list.
	#
	# The location var should be set to point to the folder holding all your galleies, not this file

	// set gallery defaults here

	private $window = 0; // open images in window: 1 = true, 0 = faulse
	private $maxcols = 5; // maximum number of colums per page
	private $location = "galleries"; // root dir of gallery relative to the file that includes this class, not this file
	private $thumbWidth = 100; // max width of thumbnails
	private	$thumbHeight = 80; // max height of thumbnails
	private $imageDisplayWidth = 640; // max width of displayed images
	private $imageDisplayHeight = 480; // max height of displayed images
	private $extensions = array('jpeg','JPEG', 'jpg','JPG', 'png','PNG'); // array of allowed file extensions
	private $showGalLinks = 1; // 0 to hide links in gallery list, 1 to show them


	// do not change below here
	private $thumbsFolder ="_thumbs";
	private $pathToGallery;
	private $galleryName;
	private $directory;
	private $numberOfFiles;
	private $thumbOBJ;

	function __construct(){
		$this->setGalName($_SESSION['galName']);
		//echo $this->galleryName;
		$this->setpathToGallery();
	}
	function setpathToGallery(){
		$this->pathToGallery = $this->location ."/". $this->galleryName;
	}
	function setGalName(){
		$this->galleryName = $_SESSION['galName'];
	}
	function getNumberOfFiles(){
		return$this->numberOfFiles;
	}
	function getGalName(){
		return $this->galleryName;
	}
	function loadThumbClass(){
		// create new thumbnail object
		require_once("classes/thumbnail.class.php");
		$this->thumbOBJ = new thumbnail();
	}
	function showGalMenu(){
		$path = $this->location;
		$out.= "<a href=\"".$_SERVER['PHP_SELF']."?gname=home\">Gallery Home</a><br>";

		if ($hd = opendir($path))
		{
			while ($sz = readdir($hd)) { if (preg_match("/^\./",$sz)==0) $dirList[] = $sz; }
			closedir($hd);
		}
		asort($dirList);

		// start html out for menu
		// not working correctly
		for ($x = 0; $x<=sizeof($dirList); $x++ ){
			// exclude the _thumbs folder from the list
			if ($dirList[$x] !=$this->thumbsFolder){
				// make sure its a directory and not a folder
				if(!is_file($path.$dirList[$x])){
					$out.= "<a href=\"".$_SERVER['PHP_SELF']."?gname=".$dirList[$x]."\">". $dirList[$x] ."</a><br>";
				}
			}
		}
		echo $out;
	}
	function getFileList ()
	{
		# build a list a imags in given directory

		// find number of files in dir
		$nextensions = sizeof($this->extensions);

		// set file array counter to 0
		$file = 0;

		// load contents of dir in to array
		$this->directory = dir ($this->pathToGallery);

		// build file list and remove directories and none listed file extenstions from the list
		while ($entry = $this->directory->read())
		{
			for ($i=0; $i<=$nextensions; $i++){
				if(is_file($this->pathToGallery."/".$entry)){
					if($this->thumbOBJ->imageis($this->pathToGallery."/".$entry) == "jpg"){
						$fileList[++$file] = $entry;
						break;
					}else {break;}
				}
			}
		}

		// unload contents of dir from memory
		$this->directory->close();

		// set number of files in gallery
		$this->numberOfFiles = sizeof($fileList);

		// return file list array
		return $fileList;
	}
	function showGallery (){
		// check to see if the home page should be displayed
		if($this->galleryName=="home"){

			// display gallery home page
			$this->galHome();

		} elseif ($this->galleryName=="info") {
			$this->galInfo();
		}
		else {//display gallery

			$this->loadThumbClass();

			// get a list of files in the gallery dir
			$fileList = $this->getFileList();

			// get the number of files in the list
			$numFiles = sizeof ($fileList);

			//make thumbs from images in gallery directory
			$thumbsdir=$this->location ."/".$this->thumbsFolder."/".$this->galleryName."/";

			// make sure the thumb dir exits, if not make it
			if (!is_dir($thumbsdir ))
			{
				mkdir($thumbsdir,0777);
			}

			//open html table
			echo ("<table width=100%>");

			// insert thumbnails with links to files, building the table as we go
			for ($i=0; $i<$numFiles;)
			{
				echo "<tr>";

				for ($cols=1; $cols<=$this->maxcols; $cols++)
				{
					// begin output string
					$out ="<td align=center>";

					// get the file name to make link to
					$imageFileName = $fileList[++$i];

					// build path/filename string to source
					$pathToSourceImage = $this->pathToGallery."/".$imageFileName;

					// build path/file name string to destination file
					$pathToDestinationImage = $thumbsdir."tn_".$imageFileName;


					// make thumbnail
					$this->thumbOBJ->makeThumbnailImage($pathToSourceImage,$pathToDestinationImage, $this->thumbHeight,$this->thumbWidth);


					// make sure we have a file name
					if ($imageFileName!="")
					{
						//$linkExt ="?showImage=".$this->pathToGallery."/".$imageFileName.
						// set path to full image
						$out .= "<a href=\"".$_SERVER['PHP_SELF']."?gname=".$this->galleryName."&showImage=".$imageFileName."\"";

						// check to see if link to open in a window or not
						if ($this->window == 1){ $out .= "target=\"_blank\">";}

						// build image link and display thumbnail
						$out .= "<img src=\"".$thumbsdir."tn_".$imageFileName;
						$out .= "\" border=\"0\"><br>";

						// show or hide image file names
						if ($this->showGalLinks =="1"){
							$out .= $fileList[$i];
							$out .= "</a><br></td>";
						} else {
							$out .= "</a></td>";
						}
						echo $out;
					}
				}
				echo "</tr>";
			}
			// close gallery table
			echo "</table>";
		}
	}
	function showImage($imageFileName){
		// load in thumbs class
		$this->loadThumbClass();
		// load in image file
		$img_details = getimagesize($this->pathToGallery."/".$imageFileName);
		$out= "w".$img_details[0]."/".$img_details[1]."h";
		// resize the image
		$imageOutputXY = $this->thumbOBJ->ratioResize(ceil($img_details[0]),ceil($img_details[1]), $this->imageDisplayWidth,$this->imageDisplayHeight);
		// output image within table and sized correctly
		$out .="<table width=\"10\" border=\"0\" align=\"center\" cellpadding=\"1\" cellspacing=\"0\" bgcolor=\"#B47E75\">";
		$out .="<tr><td><table width=\"100%\" border=\"0\" cellpadding=\"3\" cellspacing=\"0\" bgcolor=\"#5C4334\"><tr><td><div align=\"center\">";
		$out .="<img src=\"".$this->pathToGallery."/".$imageFileName."\" width=\"".$imageOutputXY[0]."\" height=\"".$imageOutputXY[1]."\">";
		$out.="</div></td></tr></table></td></tr></table>";
		
		$out .= "<br>Displaying image: $imageFileName From gallery:".$this->galleryName;
		echo $out;
	}
	function galHome(){
			echo "Display gallery home page here (imported php file)";
	}
	function CR(){
		$out ="Powered By Badley Photo Blog v0.01 &copy Leigh Edwards 2006";
		return $out;
	}
	function galInfo(){
		echo "display class info"
	}
	
	function __destruct(){
		//clean up jobs
	}

}

?>
here is the php file use to display the file on the test site here http://72.29.239.158

Code: Select all

<?php
//session_start();
if(isset($_GET['gname'])){
	$_SESSION['galName'] = $_GET['gname'];
}else{
	if(!isset($_SESSION['galName'])){
		$_SESSION['galName'] = "home";
	}
}
// load needed classes
require_once("gallery.class.php");
// create new gallery object
$gal = new gallery($_SESSION['galName']);
?>
<body bgcolor="#003366" text="#B47E75" link="#B47E75" vlink="#B47E75" alink="#B47E75" topmargin="25">
<table width="909" border="0" align="center" cellpadding="1" cellspacing="0" bgcolor="#B47E75">
  <tr> 
    <td><img src="../../images/header.jpg">
	<table width="100%" border="0" cellpadding="1" cellspacing="0" bgcolor="#5C4334">
        <tr> 
          <td width="100"></td>
          <td align="center" class="title"><div align="right"><strong><?php echo $gal->getGalName();?>::</strong></div></td>
          <td width="100"><strong>Gallery</strong></td>
        </tr>
        <tr> 
          <td width="110" height="62" valign="top" class="menu"><table width="100%" border="0" cellspacing="0" cellpadding="10">
              <tr>
                <td><table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                      <td class="menu"> 
                        <?php $gal->showGalMenu();?>
                      </td>
                    </tr>
                  </table></td>
              </tr>
            </table> </td>
          <td align="center" valign="top"><table width="100%" border="0" cellpadding="1" cellspacing="0" bgcolor="#B47E75">
              <tr> 
                <td><table width="100%" border="0" cellpadding="1" cellspacing="0" bgcolor="#5C4334">
                    <tr> 
                      <td align="center" vlign="top">
                            <?php 
                            if(isset($_GET['showImage'])){
                            	// open table to display image
                            	echo"<table width=\"10\" border=\"0\" align=\"center\" cellpadding=\"20\" cellspacing=\"0\"><tr><td height=\"77\" class=\"subtext\">";
                            	// show the image
                            	$gal->showImage($_GET['showImage']);
                            	// clase the table
                            	echo "</td></tr></table>";
                            }
                            $gal->showGallery();
                          	?>
                        </td>
                    </tr>
                  </table></td>
              </tr>
            </table>
            <p align="left" class="subtext"> 
              <?php  
              if ($_SESSION['galName'] != "home"){
              	echo "Number of images: ". $gal->getNumberOfFiles();
			  }
			  ?>
            </p></td>
          <td width="100" valign="top">&nbsp;</td>
        </tr>
        <tr> 
          <td colspan="3" align="center" valign="top" class="menu"><font size="-3">All images within this gallery are the propety of krista James</font></td>
        </tr>
      </table></td>
  </tr>
</table>
<table width="909" border="0" align="center" cellpadding="1" cellspacing="0">
  <tr>
    <td>
      <div align="right"> 
        <p class="subtext">
        <?php // display copyright info
			  echo $gal->CR();
		?></p>
      </div></td>
  </tr>
</table>
and the thumbnail class as well: )


Code: Select all

<?php
# thumbnail.class.php v0.01
#
# DEBUG VERSION, NOT FOR RELEASE
# PLEASE DO NOT USE THIS CODE IN ANY PRODUNCTION SCRIPTS.
# THIS CODE HAS NOT BEEN TESTED AND MAY BE UNSTABLE

# thumbnail . class for php 5+ by leigh edwards March 2006
# Please send any information on any problems you encounter to
# leighjedwards@msn.com
class thumbnail {


	function makeThumbnailImage($pathToSourceImage,$pathToThumbImage, $thumbHeight, $thumbWidth)
	{
		if (!is_file($pathToThumbImage)){
			// get image type
			$imageType = $this->imageis($pathToSourceImage);
			if( $imageType == "jpg"){

				// get source image dimentions
				$img_details = getimagesize($pathToSourceImage);
				$src_img = imagecreatefromjpeg($pathToSourceImage);
				// calutlate the size of out put file, maintaining aspect ratio
				$thumbXY = $this->ratioResize($img_details[0],$img_details[1],$thumbWidth,$thumbHeight);

				$dst_img= imagecreatetruecolor($thumbXY[0],$thumbXY[1]);

				//$src_img = imagecreatefromjpeg($pathToSourceImage);

				imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumbXY[0],$thumbXY[1],$img_details[0],$img_details[1]);
				// write image to Thumb file
				imagejpeg($dst_img,$pathToThumbImage);

				// remove image from ram
				imagedestroy($dst_img);
				imagedestroy($src_img);
			}
		}
	}


	function ratioResize($imageWidth,$imageHeight, $maxThumbX, $maxThumbY){
		// returns array with new image size fiting within $maxThumbX/$maxThumbY ratio
		$width_ratio=($imageWidth/$maxThumbX);
		$height_ratio=($imageHeight/$maxThumbY);

		if($width_ratio >=$height_ratio)
		{
			$ratio=$width_ratio;
		}
		else
		{
			$ratio=$height_ratio;
		}

		$imageXY[0]=($imageWidth/$ratio);
		$imageXY[1]=($imageHeight/$ratio);
		return $imageXY;
	}

	function imageis($fileName){

		// returns simple Logical image type instead of numric value
		$imagetype=false;
		$img_details = getimagesize($fileName);
		if($img_details[2] == 2){$imagetype="jpg";}
		elseif($img_details[2] == 1){$imagetype="gif";}
		elseif($img_details[2] == 3){$imagetype="png";}
		elseif($img_details[2] == 4){$imagetype="swf";}
		elseif($img_details[2] == 5){$imagetype="psd";}
		elseif($img_details[2] == 6){$imagetype="bmp";}
		elseif($img_details[2] == 7){$imagetype="intelTiff";}
		elseif($img_details[2] == {$imagetype="MotoTiff";}
		elseif($img_details[2] == 9){$imagetype="jpc";}
		elseif($img_details[2] == 10){$imagetype="jp2";}
		elseif($img_details[2] == 11){$imagetype="jpx";}
		elseif($img_details[2] == 12){$imagetype="jb2";}
		elseif($img_details[2] == 13){$imagetype="swc";}
		elseif($img_details[2] == 14){$imagetype="iff";}
		elseif($img_details[2] == 15){$imagetype="wbmp";}
		elseif($img_details[2] == 16){$imagetype="xbm";}
		return $imagetype;
	}
}

	?>

If ne1 actualy has time to read through all that, please let me know any way to fix the known bugs, or just make the whole thing run faster.
thnaks