Hi,
Please help me to get images in table format. I'm new to PHP.
I have written code to display images in a table format and it displays only 9 images in a single page. when i click Next Url to go to next page, by default it returns to home page. I stored images in local directory and written for each loop to display images in table format. Without using mysql as backend.
My question is how to display bunch of images in table formated (3x3) column and rows format with next link to navigate to the next page?
My code is as :
When i click next it goes to home page.
My Page Navigator code is as :
My Directory Items code is as:
My ThumbnailImage code is as :
My Getthumb code is as :
Please help! Thanks in advance!
Please help me to get images in table format. I'm new to PHP.
I have written code to display images in a table format and it displays only 9 images in a single page. when i click Next Url to go to next page, by default it returns to home page. I stored images in local directory and written for each loop to display images in table format. Without using mysql as backend.
My question is how to display bunch of images in table formated (3x3) column and rows format with next link to navigate to the next page?
My code is as :
Code:
<?php
/* final code for use with directoritems class after navigator
is created */
require 'PageNavigator.php';
require 'DirectoryItems.php';
//max per page
define("PERPAGE", 9);
//name of first parameter in query string
define("OFFSET", "offset");
/*get query string - name should be same as first parameter name
passed to the page navigator class*/
$offset=@$_GET[OFFSET];
//check variable
if (!isset($offset))
{
$totaloffset=0;
}
else
{
//clean variable here
//then calc record offset
$totaloffset = $offset * PERPAGE;
}
$di = new DirectoryItems("My Directory name");
$di->imagesOnly();
$di->naturalCaseInsensitiveOrder();
//get portion of array
$filearray = $di->getFileArraySlice($totaloffset, PERPAGE);
echo "<div style=\"text-align:center;\">";
//echo "Click the file name to view full-sized version.<br />";
$path = "";
//specify size of thumbnail
$size = 100;
//use SEPARATOR
echo "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"1\"><tr>";
$imgcount=0;
foreach ($filearray as $key => $value)
{
echo "<td align=\"center\" width=\"33%\" valign=\"top\">";
$path = "{$di->getDirectoryName()}/$key";
/*errors in getthumb or in class will result in broken links
- error will not display*/
echo "<img src=\"getthumb.php?path=$path&size=$size\" width=\"100\" height=\"100\" ".
"alt=\"$value\" /><br />\n";
echo "<a href=\"$path\" target=\"_blank\" >";
echo "$value</a><br><br><br />\n";
echo "</td>";
$imgcount++;
if ($imgcount%3==0)
{
echo "</tr><tr>";
}
}
echo "</tr></table>";
echo "</div><br />";
$pagename = basename($_SERVER["PHP_SELF"]);
$totalcount = $di->getCount();
$numpages = ceil($totalcount/PERPAGE);
//create if needed
if($numpages > 1)
{
//create navigator
$nav = new PageNavigator($pagename, $totalcount, PERPAGE, $totaloffset);
//is the default but make explicit
$nav->setFirstParamName(OFFSET);
echo $nav->getNavigator();
}
?>
My Page Navigator code is as :
Code:
<?php
////////////////////////////////////////////////////////////////////
/**
Class for navigating over multiple pages
*/
class PageNavigator{
//data members
private $pagename;
private $totalpages;
private $recordsperpage;
private $maxpagesshown;
private $currentstartpage;
private $currentendpage;
private $currentpage;
//next and previous inactive
private $spannextinactive;
private $spanpreviousinactive;
//first and last inactive
private $firstinactivespan;
private $lastinactivespan;
//must match $_GET['offset'] in calling page
private $firstparamname = "offset";
//use as "&name=value" pair for getting
private $params;
//css class names
private $inactivespanname = "inactive";
private $pagedisplaydivname = "totalpagesdisplay";
private $divwrappername = "navigator";
//text for navigation
private $strfirst = "|<";
private $strnext = "Next";
private $strprevious = "Prev";
private $strlast = ">|";
//for error reporting
private $errorstring;
////////////////////////////////////////////////////////////////////
//constructor
////////////////////////////////////////////////////////////////////
public function __construct($pagename, $totalrecords, $recordsperpage, $recordoffset, $maxpagesshown = 4, $params = ""){
$this->pagename = $pagename;
$this->recordsperpage = $recordsperpage;
$this->maxpagesshown = $maxpagesshown;
//already urlencoded
$this->params = $params;
//check recordoffset a multiple of recordsperpage
$this->checkRecordOffset($recordoffset, $recordsperpage) or
die($this->errorstring);
$this->setTotalPages($totalrecords, $recordsperpage);
$this->calculateCurrentPage($recordoffset, $recordsperpage);
$this->createInactiveSpans();
$this->calculateCurrentStartPage();
$this->calculateCurrentEndPage();
}
////////////////////////////////////////////////////////////////////
//public methods
////////////////////////////////////////////////////////////////////
//give css class name to inactive span
////////////////////////////////////////////////////////////////////
public function setInactiveSpanName($name){
$this->inactivespanname = $name;
//call function to rename span
$this->createInactiveSpans();
}
////////////////////////////////////////////////////////////////////
public function getInactiveSpanName(){
return $this->inactivespanname;
}
////////////////////////////////////////////////////////////////////
public function setPageDisplayDivName($name){
$this->pagedisplaydivname = $name;
}
////////////////////////////////////////////////////////////////////
public function getPageDisplayDivName(){
return $this->pagedisplaydivname;
}
////////////////////////////////////////////////////////////////////
public function setDivWrapperName($name){
$this->divwrappername = $name;
}
////////////////////////////////////////////////////////////////////
public function getDivWrapperName(){
return $this->divwrappername;
}
////////////////////////////////////////////////////////////////////
public function setFirstParamName($name){
$this->firstparamname = $name;
}
////////////////////////////////////////////////////////////////////
public function getFirstParamName(){
return $this->firstparamname;
}
////////////////////////////////////////////////////////////////////
/**
Returns HTML code for the navigator
*/
public function getNavigator(){
//wrap in div tag
$strnavigator = "<div class=\"$this->divwrappername\">\n";
//output movefirst button
if($this->currentpage == 0){
$strnavigator .= $this->firstinactivespan;
}else{
$strnavigator .= $this->createLink(0, $this->strfirst);
}
//output moveprevious button
if($this->currentpage == 0){
$strnavigator .= $this->spanpreviousinactive;
}else{
$strnavigator.= $this->createLink($this->currentpage-1, $this->strprevious);
}
//loop through displayed pages from $currentstart
for($x = $this->currentstartpage; $x < $this->currentendpage; $x++){
//make current page inactive
if($x == $this->currentpage){
$strnavigator .= "<span class=\"$this->inactivespanname\">";
$strnavigator .= $x+1;
$strnavigator .= "</span>\n";
}else{
$strnavigator .= $this->createLink($x, $x+1);
}
}
//next button
if($this->currentpage == $this->totalpages-1){
$strnavigator .= $this->spannextinactive;
}else{
$strnavigator .= $this->createLink($this->currentpage + 1, $this->strnext);
}
//move last button
if($this->currentpage == $this->totalpages-1){
$strnavigator .= $this->lastinactivespan;
}else{
$strnavigator .= $this->createLink($this->totalpages -1, $this->strlast);
}
$strnavigator .= "</div>\n";
$strnavigator .= $this->getPageNumberDisplay();
return $strnavigator;
}
////////////////////////////////////////////////////////////////////
//private methods
////////////////////////////////////////////////////////////////////
private function createLink($offset, $strdisplay ){
$strtemp = "<a href=\"$this->pagename?$this->firstparamname=";
$strtemp .= $offset;
$strtemp .= "$this->params\">$strdisplay</a>\n";
return $strtemp;
}
////////////////////////////////////////////////////////////////////
private function getPageNumberDisplay(){
$str = "<div class=\"$this->pagedisplaydivname\">\nPage ";
$str .= $this->currentpage+1;
$str .= " of $this->totalpages";
$str .= "</div>\n";
return $str;
}
////////////////////////////////////////////////////////////////////
private function setTotalPages($totalrecords, $recordsperpage){
$this->totalpages = ceil($totalrecords/$recordsperpage);
}
////////////////////////////////////////////////////////////////////
private function checkRecordOffset($recordoffset, $recordsperpage){
$bln = true;
if($recordoffset%$recordsperpage != 0){
$this->errorstring = "Error - not a multiple of records per page.";
$bln = false;
}
return $bln;
}
////////////////////////////////////////////////////////////////////
private function calculateCurrentPage($recordoffset, $recordsperpage){
$this->currentpage = $recordoffset/$recordsperpage;
}
////////////////////////////////////////////////////////////////////
// not always needed but create anyway
////////////////////////////////////////////////////////////////////
private function createInactiveSpans(){
$this->spannextinactive = "<span class=\"".
"$this->inactivespanname\">$this->strnext</span>\n";
$this->lastinactivespan = "<span class=\"".
"$this->inactivespanname\">$this->strlast</span>\n";
$this->spanpreviousinactive = "<span class=\"".
"$this->inactivespanname\">$this->strprevious</span>\n";
$this->firstinactivespan = "<span class=\"".
"$this->inactivespanname\">$this->strfirst</span>\n";
}
////////////////////////////////////////////////////////////////////
// find start page based on current page
////////////////////////////////////////////////////////////////////
private function calculateCurrentStartPage(){
$temp = floor($this->currentpage/$this->maxpagesshown);
$this->currentstartpage = $temp * $this->maxpagesshown;
}
////////////////////////////////////////////////////////////////////
private function calculateCurrentEndPage(){
$this->currentendpage = $this->currentstartpage+$this->maxpagesshown;
if($this->currentendpage > $this->totalpages)
{
$this->currentendpage = $this->totalpages;
}
}
}//end class
////////////////////////////////////////////////////////////////////
?>
Code:
<?php
class DirectoryItems
{
//data members
private $filearray = array();
private $replacechar;
private $directory;
public function __construct($directory, $replacechar = "_")
{
$this->directory = $directory;
$this->replacechar = $replacechar;
$d = "";
if(is_dir($directory))
{
$d = opendir($directory) or die("Failed to open directory.");
while(false !== ($f = readdir($d)))
{
if(is_file("$directory/$f"))
{
$title = $this->createTitle($f);
$this->filearray[$f] = $title;
}
}
closedir($d);
}
else
{
//error
die("Must pass in a directory.");
}
}
//////////////////////////////////////////////////////////////////
//destructor
//////////////////////////////////////////////////////////////////
public function __destruct()
{
unset($this->filearray);
}
//////////////////////////////////////////////////////////////////
//public fuctions
//////////////////////////////////////////////////////////////////
public function getDirectoryName()
{
return $this->directory;
}
//////////////////////////////////////////////////////////////////
public function indexOrder()
{
sort($this->filearray);
}
//////////////////////////////////////////////////////////////////
public function naturalCaseInsensitiveOrder()
{
natcasesort($this->filearray);
}
//////////////////////////////////////////////////////////////////
//returns false if files are not all images of these types
//////////////////////////////////////////////////////////////////
public function checkAllImages()
{
$bln = true;
$extension = "";
$types = array("jpg", "jpeg", "gif", "png");
foreach ($this->filearray as $key => $value)
{
$extension = substr($key,(strpos($key, ".")+1));
$extension = strtolower($extension);
if(!in_array($extension, $types))
{
$bln = false;
break;
}
}
return $bln;
}
//////////////////////////////////////////////////////////////////
//returns false if not all specified extension
//////////////////////////////////////////////////////////////////
public function checkAllSpecificType($extension)
{
$extension = strtolower($extension);
$bln = true;
$ext = "";
foreach ($this->filearray as $key => $value)
{
$ext = substr($key,(strpos($key, ".")+1));
$ext = strtolower($ext);
if($extension != $ext)
{
$bln=false;
break;
}
}
return $bln;
}
//////////////////////////////////////////////////////////////////
public function getCount()
{
return count($this->filearray);
}
//////////////////////////////////////////////////////////////////
public function getFileArray()
{
return $this->filearray;
}
//////////////////////////////////////////////////////////////////
//for use with navigator - Phase 3
/////////////////////////////////////////////////////////////////
public function getFileArraySlice($start, $length)
{
return array_slice($this->filearray, $start, $length);
}
//////////////////////////////////////////////////////////////////
//eliminate all elements from array except specified extension - Phase 2
/////////////////////////////////////////////////////////////////
public function filter($extension)
{
$extension = strtolower($extension);
foreach ($this->filearray as $key => $value)
{
$ext = substr($key,(strpos($key, ".") + 1));
$ext = strtolower($ext);
if($ext != $extension)
{
unset($this->filearray[$key]);
}
}
}
//////////////////////////////////////////////////////////////////
//eliminate all elements from array except images - Phase 2
/////////////////////////////////////////////////////////////////
public function imagesOnly()
{
$extension = "";
$types = array("jpg", "jpeg", "gif", "png");
foreach ($this->filearray as $key => $value)
{
$extension = substr($key,(strpos($key, ".") + 1));
$extension = strtolower($extension);
if(!in_array($extension, $types))
{
unset($this->filearray[$key]);
}
}
}
//////////////////////////////////////////////////////////////////
//recreate array after filtering - Phase 2
/////////////////////////////////////////////////////////////////
public function removeFilter()
{
unset($this->filearray);
$d = "";
$d = opendir($this->directory) or die($php_errormsg);
while(false!==($f=readdir($d)))
{
if(is_file("$this->directory/$f"))
{
$title = $this->createTitle($f);
$this->filearray[$f] = $title;
}
}
closedir($d);
}
//////////////////////////////////////////////////////////////////
//private functions
/////////////////////////////////////////////////////////////////
private function createTitle($title)
{
//strip extension
$title = substr($title,0,strrpos($title, "."));
//replace word separator
$title = str_replace($this->replacechar, " ", $title);
return $title;
}
}//end class
?>
Code:
<?php
//requires GD 2.0.1 or higher
//note about gif
class ThumbnailImage
{
private $image;
//not applicable to gif
private $quality = 100;
private $mimetype;
private $imageproperties;
private $initialfilesize;
////////////////////////////////////////////////////////
//constructor
////////////////////////////////////////////////////////
public function __construct($file, $thumbnailsize = 100)
{
//check path
is_file($file) or die ("File: $file doesn't exist.");
$this->initialfilesize = filesize($file);
$this->imageproperties = getimagesize($file) or die ("Incorrect file type.");
// new function image_type_to_mime_type
$this->mimetype = image_type_to_mime_type($this->imageproperties[2]);
//create image
switch($this->imageproperties[2]){
case IMAGETYPE_JPEG:
$this->image = imagecreatefromjpeg($file);
break;
case IMAGETYPE_GIF:
$this->image = imagecreatefromgif($file);
break;
case IMAGETYPE_PNG:
$this->image = imagecreatefrompng($file);
break;
default:
die("Couldn't create image.");
}
$this->createThumb($thumbnailsize);
}
////////////////////////////////////////////////////////
//destructor
////////////////////////////////////////////////////////
public function __destruct()
{
if(isset($this->image))
{
imagedestroy($this->image);
}
}
////////////////////////////////////////////////////////
//public methods
////////////////////////////////////////////////////////
public function getImage()
{
header("Content-type: $this->mimetype");
switch($this->imageproperties[2])
{
case IMAGETYPE_JPEG:
imagejpeg($this->image,"",$this->quality);
break;
case IMAGETYPE_GIF:
imagegif($this->image);
break;
case IMAGETYPE_PNG:
imagepng($this->image,"",$this->quality);
break;
default:
die("Couldn't create image.");
}
}
////////////////////////////////////////////////////////
public function getMimeType(){
return $this->mimetype;
}
////////////////////////////////////////////////////////
public function getQuality()
{
$quality = null;
if($this->imageproperties[2] == IMAGETYPE_JPEG || $this->imageproperties[2] == IMAGETYPE_PNG)
{
$quality = $this->quality;
}
return $quality;
}
////////////////////////////////////////////////////////
public function setQuality($quality)
{
if($quality > 100 || $quality < 1)
{
$quality = 75;
}
if($this->imageproperties[2] == IMAGETYPE_JPEG || $this->imageproperties[2] == IMAGETYPE_PNG)
{
$this->quality = $quality;
}
}
////////////////////////////////////////////////////////
public function getInitialFileSize()
{
return $this->initialfilesize;
}
////////////////////////////////////////////////////////
//private methods
////////////////////////////////////////////////////////
private function createThumb($thumbnailsize)
{
//array elements
$srcW = $this->imageproperties[0];
$srcH = $this->imageproperties[1];
//only adjust if larger than reduction size
if($srcW >$thumbnailsize || $srcH > $thumbnailsize)
{
$reduction = $this->calculateReduction($thumbnailsize);
//get proportions
$desW = $srcW/$reduction;
$desH = $srcH/$reduction;
$copy = imagecreatetruecolor($desW, $desH);
imagecopyresampled($copy,$this->image,0,0,0,0,$desW, $desH, $srcW, $srcH)
or die ("Image copy failed.");
//destroy original
imagedestroy($this->image);
$this->image = $copy;
}
}
////////////////////////////////////////////////////////
private function calculateReduction($thumbnailsize)
{
//adjust
$srcW = $this->imageproperties[0];
$srcH = $this->imageproperties[1];
if($srcW < $srcH)
{
$reduction = round($srcH/$thumbnailsize);
}
else
{
$reduction = round($srcW/$thumbnailsize);
}
return $reduction;
}
}//end class
////////////////////////////////////////////////////////
?>
Code:
<?php
//this file will be the src for an img tag
require 'ThumbnailImage.php';
$path = @$_GET["path"];
$maxsize = @$_GET["size"];
if(!isset($maxsize))
{
$maxsize=100;
}
if(isset($path))
{
$thumb = new ThumbNailImage($path, $maxsize);
$thumb->getImage();
}
?>
Comment