I've written a few classes to help me make the adjustment to OOP in PHP and also get away from me being used to writing in PHP3 and 4 functions which have been depreciated along time ago.
Just realized this is a really long post, sorry, but i did cut out a lot of the junk that is not used if that helps.
The idea eventually is to have them replace my current code on my latest popular web site 🙂 and it is terrible.
The first is a basic image handler with 3 functions, one to get the dimensions and filesize, one to get the image type and another to resize the image. once all the functions of the site are completely done, i was thinking about adding watermarking and such to this class.
class imageHandler
class imageHandler
{
// get the width(x),height(y) and filesize of an image
function sizeofImage ($pathtoImage)
{
$s = getimagesize($pathtoImage);
$size['x'] = $s[0];
$size['y'] = $s[1];
$size['filesize'] = filesize($pathtoImage);
return $size;
}
// get the image type by reading the first line of the file
// and looking for image markers.
// there are better ways of doing this but my version of PHP is lacking
// the correct options.
function typeofImage ($pathtoImage)
{
$fp = fopen($pathtoImage,"r");
$data = fread($fp,1024);
fclose($fp);
if (eregi("PNG",$data))
{
$type = "image/png";
#} else if(eregi("JFIF",$data)) {
} else if (strstr($data,"JFIF")) {
$type = "image/jpeg";
} else if(eregi("GIF",$data)) {
$type = "image/gif";
} else {
$type = "not found";
}
return $type;
}
// resize an image from source file to destination file to a specified width(x)
function resizeImage($source,$dest,$x)
{
// get the sizes and type of the image
$size = $this->sizeofImage($source);
$type = $this->typeofImage($source);
// set the new height(y) of image
$y = (int) (($x / $size['x']) * $size['y']);
// create the image area
$imageDest = imagecreatetruecolor($x, $y);
// check the type of image so we know what to do next
if($type === "image/jpeg")
{
$imageOrg = imagecreatefromjpeg($source);
imagecopyresampled($imageDest, $imageOrg, 0, 0, 0, 0, $x, $y, $size['x'], $size['y']);
imagejpeg($imageDest,$dest,'100') or die("Could not make image");
} else if($type === "image/png") {
$imageOrg = imagecreatefrompng($source);
imagecopyresampled($imageDest, $imageOrg, 0, 0, 0, 0, $x, $y, $size['x'], $size['y']);
imagepng($imageDest,$dest,'100') or die("Could not make image");
} else if($type === "image/gif") {
$imageOrg = imagecreatefromgif($source);
imagecopyresampled($imageDest, $imageOrg, 0, 0, 0, 0, $x, $y, $size['x'], $size['y']);
imagepng($imageDest,$dest,'100') or die("Could not make image");
}
// remove image from memory...
// god i wish i could just remove images from my memory.
// imagine how nice it would be not to have to have that mental
// picture of that guy getting his head stuck up that elephants arse
// or that mental image of your parents doing the nasty in the kitchen
// with your best friends cousin when you came home when practice was
// done early. God please give me an imagedestroy() for my brain!!!
// Amen.
imagedestroy($imageDest);
return TRUE;
}
}
the next class stores an image, now currently i use a database but i figured i would write one for normal files too (since i was bored anyway). if thumbnail is set to yes (defaults to no) then call imageHandlers resize function and safe the thumbnail.
class imageStorage
class imageStorage
{
// uploadedFile: the uploaded file tmp name
// dest: where to save the image, any writeable directory
// thumb: whether to generate a thumbnail or not. (default: No, set to Yes for a 100px wide thumbnail)
function storeasFile($uploadedFile,$dest,$thumb="No")
{
// quick security check.
#if(!is_uploaded_file($uploadedFile)) {
# die ("File not uploaded by this script.\n<br>Possible Hack attempt, This session has been logged.\n");
# // note, it really hasn't... yet
#}
// move the image to the destination
move_uploaded_file($uploadedFile,$dest);
// if Thumb is set run the thumbnail generation from imagehandler class
if($thumb !== "No")
{
// create thumbnail name I think theres an easier way to do this with regex
// but i'm too tired to care right now, and this works
$pinfo = pathinfo($dest);
$fileExten = "." . $pinfo[extension];
$thumbname = ereg_replace($fileExten,"_thmb".$fileExten,$dest);
// create and save the thumb nail
$ih = new imageHandler();
$ih->resizeImage($dest,$thumbname,'100');
}
}
// Config file: See sample_db_config.php
// source: the uploaded file tmp name
// dest: in this case the only thing this is used for is the filename
// thumb: whether to generate a thumbnail or not. (default: No, set to Yes for a 100px wide thumbnail)
// you can add columns to the insert just make sure you look at the sample_db_config.php
function storeinDB($dbConfigFile,$source,$dest,$thumb="No")
{
// setting up the data to put into the databas
$ipaddy = $_SERVER['REMOTE_ADDR'];
$filename = $dest;
$ih = new imageHandler();
$filetype = $ih->typeofImage($source);
$size = $ih->sizeofImage($source);
$filesize = $size['filesize'];
require($dbConfigFile);
$db = MYSQL_CONNECT($server,$user,$pass) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
// setting up data for the image
#$image = mysql_real_escape_string(fread(fopen($source,"r"),$filesize));
$image = mysql_real_escape_string(file_get_contents($source,FILE_BINARY));
//setup data for the thumbnail
if ($thumb !== "No")
{
// create the thumbnail, setup the string
$pinfo = pathinfo($dest);
$fileExten = "." . $pinfo[extension];
$thumbname = ereg_replace($fileExten,"_thmb".$fileExten,$dest);
$ih->resizeImage($source,'/tmp/'.$thumbname,'100');
$thumb = mysql_real_escape_string(file_get_contents('/tmp/'.$thumbname,FILE_BINARY));
} else if($thumb ==="No") {
$thumb = ""; // no more thumbs.. kinda like diVinci
}
// Connect to database (using the config file) and upload the image.
$sql="INSERT INTO $table (ipaddy,filename,filesize,filetype,thumb,image) VALUES ('$ipaddy','$filename','$filesize','$filetype','$thumb','$image')";
$result=mysql_query($sql) or die ("Could not insert data: " . mysql_error());
mysql_close($db);
return TRUE;
}
}
the last is galleryHandler, this allows you to show the thumbnails on a page. Works great for the Database cause pagination was so easy but for files i'm stuck. I may say screw it and not use that option because I don't feel like figureing it out :-) if you have an idea on how i should do it yell. But i really don't care cause I like the database storage better.
class galleryHandler
class galleryHandler
{
// figures out how many pages to set up based on total images in table (in the config) and number per page
function getNumberPages ($dbConfigFile,$perpage)
{
// connect to mysql, retrieve the id field and then count the results
require($dbConfigFile);
$db = MYSQL_CONNECT($server,$user,$pass) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$numRows = mysql_num_rows(mysql_query("SELECT id FROM $table",$db));
return $numPages = ceil($numRows / $perpage);
}
// display the thumb nails
function displayDBThumbs ($dbConfigFile,$start,$perpage)
{
require($dbConfigFile);
$db = MYSQL_CONNECT($server,$user,$pass) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
$sql = "SELECT id,filename,filesize FROM ". $table . " LIMIT " . $start . "," . $perpage;
$result=mysql_query($sql,$db) or die (mysql_error());
while ($myrow=mysql_fetch_array($result))
{
echo "<img src=viewthumb.php?id=" . $myrow['id'] . "&cat=". $table . ">";
}
}
// config file as usual, number of thumbs to show per page and
// the url to show the pages on. (usually $PHP_SELF)
function createDBLinks($dbConfigFile,$perpage,$url)
{
$numPages = $this->getNumberPages ($dbConfigFile,$perpage);
$next =0;
for ($i=1; $i<=$numPages; $i++)
{
echo "<a href=" . $url . "?start=" . $next . ">" . $i . "</a> ";
$next = $next + $perpage;
}
}
function getFileThumbs($directory)
{
$dh = opendir($directory) or die("Could not open directory");
while (($file = readdir($dh)) !== false)
{
if (ereg("_thmb",$file))
{
$thmbArray[] = $file;
}
}
return $thmbArray;
}
function displayFileThumbs($directory,$start,$perpage,$thmbArray)
{
$show = array_slice($thmbArray,0,$perpage);
foreach ($show as $show)
{
echo "<img src=" . $show . ">";
}
}
}
Thanks for any feed back and improvements!
Joe