Storage and Re-use of Images Using PHP/GD - Part 2
Following up on part 1 of this compelling two part series on image handling, Gijs will now supply DevArticles readers some code snippets that will demonstrate the significance of his work.
Storage and Re-use of Images Using PHP/GD - Part 2 - The Article (Page 2 of 3 )
What we Will do in this Second Part
We will write scripts that allow us to:
automatically generate an appropriate img tag for an image;
search and find our images;
a popup that shows us a larger version of an image. (This isn't that difficult, but it's a nice example of how we can use our scripts to create img tags.)
Creating the img Tag
First, we need a function that, when provided with an image name, does this:
looks up the image information in the database;
calculates the height and width of the image after resizing;
builds the URL to the image retrieval script;
combines these three parts in a nice img tag for use in our html.
The Function
In imgtag.php, we start with defining the name of the table containing the image info and connecting to the database. Then, we open a function called img_tag, that will return the img tag.
// define database table containing image info $img_table = "images"; // connect with database mysql_connect("yourhost", "youruser", "password"); mysql_select_db("yourdb"); // generates and returns an img-tag function img_tag($img_file, $attrib) { global $img_table;
To create an img tag, our function needs the following arguments passed:
$img_file: the 13-character filename of the image, as saved in the database and in the filesystem;
$attrib: an array describing how we want the image to be. This associative array consists of the same one-letter keys we used in the resize script.
Preserving the Attributes
Not only will the information in $attrib be used in this function, but it will also get passed to the image resize script. The data in $attrib gets changed later in the function, so we should preserve it now to put it in the img tag. The values in the array get concatenated and saved as a string in $attribs.
// concatenate the attributes in $attrib $attribs = ""; foreach ($attrib as $key => $value) { $attribs .= '+'."$key($value)"; }
Retrieving the Image from the Database
Now, we have to look in the database and see if our image can be found. We use the provided $img_name to find the right entry.
// retrieve image info from database $result = mysql_query("SELECT * FROM $img_table ". "WHERE img_file='$img_file'"); // check that an entry is found if (mysql_num_rows($result)!=1) { return false; } // get this row $img_info = mysql_fetch_array($result); Calculating Image Height and Width
We've got the image information in the $img_info array. We've also got any possible resize instructions in the $attrib array. Using this information, we can calculate what proportions the image will have. We can then specify the height and width in our img tag.
We use a slightly modified version of the code we used in the image resize script to calculate the new width and height.
// check for maximum width and height if (isset($attrib["x"])) { if ($attrib["x"] < $img_info["img_width"]) { $attrib["w"] = $attrib["x"]; } } if (isset($attrib["y"])) { if ($attrib["y"] < $img_info["img_height"]) { $attrib["h"] = $attrib["y"]; } } // check for need to resize // convert relative to absolute if (isset($attrib["w"])) { if (strstr($attrib["w"], "%")) { $attrib["w"] = (intval(substr($attrib["w"], 0, -1)) / 100) * $img_info["img_width"]; } } if (isset($attrib["h"])) { if (strstr($attrib["h"], "%")) { $attrib["h"] = (intval(substr($attrib["h"], 0, -1)) / 100) * $img_info["img_height"]; } } // resize if (isset($attrib["w"]) and isset($attrib["h"])) { $out_w = $attrib["w"]; $out_h = $attrib["h"]; } elseif (isset($attrib["w"]) and !isset($attrib["h"])) { $out_w = $attrib["w"]; $out_h = $img_info["img_height"] * ($attrib["w"] / $img_info["img_width"]); } elseif (!isset($attrib["w"]) and isset($attrib["h"])) { $out_w = $img_info["img_width"] * ($attrib["h"] / $img_info["img_height"]); $out_h = $attrib["h"]; } else { $out_w = $img_info["img_width"]; $out_h = $img_info["img_height"]; }
The img Tag
The last thing our function has to do, is actually create the img tag and return that.
// create and return the img-tag $img = '<img src="img.php?f('.$img_file.')'.$attribs.'" '. 'width="'.$out_w.'" height="'.$out_h.'" '. 'alt="'.$img_info["img_alt"].'" border="0">'; return $img; }
The Search Form
To search the images, we start with a simple form. We can search by title, description, alt-text and image size. Save the form as, for example, search.html. You can change the form to suit your needs, but basically it would look like this:
The input from the search form is sent to search.php. We will write this script now. After doing a search, it should return the images with the appropriate data. The user should also be able to click on the images for a popup larger version.
The first step is the inclusion of the img tag-script. Normally, you would also have to connect to the database. We already did that in the included script, so that's not necessary here.
include("imgtag.php");
The Query
Using the data posted by the form, we can now build a search query. (We only search for width, height and bytes if a value is given.)
// build query $query = "SELECT * FROM images WHERE "; // title $query .= "img_title LIKE '%".$HTTP_POST_VARS["title"]."%' AND "; // description $query .= "img_descr LIKE '%".$HTTP_POST_VARS["descr"]."%' AND "; // alt $query .= "img_alt LIKE '%".$HTTP_POST_VARS["alt"]."%' AND "; // width if (trim($HTTP_POST_VARS["width"])!="") { $query .= "img_width".$HTTP_POST_VARS["width_expr"]. $HTTP_POST_VARS["width"]." AND "; } // height if (trim($HTTP_POST_VARS["height"])!="") { $query .= "img_height".$HTTP_POST_VARS["height_expr"]. $HTTP_POST_VARS["height"]." AND "; } // bytes if (trim($HTTP_POST_VARS["bytes"])!="") { $query .= "img_bytes".$HTTP_POST_VARS["bytes_expr"]. $HTTP_POST_VARS["bytes"]." AND "; } // type $query .= "img_alt LIKE '%".$HTTP_POST_VARS["type"]."%' AND "; // finish the query (we ended every part with AND) $query .= "1";
Execute and count the results:
// execute the query $result = mysql_query($query); // get the number of results $num_rows = mysql_num_rows($result); The Results
We start with a basic html-page. We also include a JavaScript function (borrowed from www.vpro.nl) to display the popup with a larger version of the image.
?><html> <script language="javascript"> /* source: www.vpro.nl */ function bigImage(name) { if (navigator.appName=="Netscape") { var imagewindow = window.open('bigimage.php?f='+name,'imagewindow'+name, 'resizable=yes,scrollbars=no,status=1,innerWidth=450,innerHeight=402'); } else { var imagewindow = window.open('bigimage.php?f='+name,'imagewindow'+name, 'resizable=yes,scrollbars=yes,status=1,width=450,height=402'); } } </script> <body> <h1>Search Results</h1> <table><?php
Per image, we display one table row. We add a popup link to bigimage.php, a script that displays a larger version of the image. We just link to it for now, we will write bigimage.php in the next step. The img_tag function is used to generate the img tag.
// one row for each result for ($i=0; $i<$num_rows; $i++) { // fetch row $img_info = mysql_fetch_array($result); // start table row echo '<tr><td><a href="bigimage.php?f='.$img_info["img_file"].'" '. 'target="_new" onclick="bigImage('."'".$img_info["img_file"]."')". '; return false;">'; // generate the image tag echo img_tag($img_info["img_file"], array("x"=>"250")); // echo image information echo "</a></td><td><b>".$img_info["img_title"]."</b><br>". $img_info["img_descr"]."<hr><b>Alt:</b> ".$img_info["img_alt"]. "<br><b>Pixels:</b> ".$img_info["img_width"]."x". $img_info["img_height"]."<br><b>Bytes:</b> ". $img_info["img_bytes"]."<br><b>Type:</b> ". $img_info["img_type"]."</td></tr>\n"; }
Now just close the table, body and html tags and your search script is finished.
Bigimage.php
As said, this script isn't very complicated. It uses the img_tag function to display a larger version of the image. That image links to the full-size version of the image. Save the code as bigimage.php and you're ready.