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"];
}