Loading the Image
The next step is the actual loading of the image. The getimagesize(); function is used to determine the file type, and then the correct method is used to load the image. In case the requested type of the returned image is not given, the file type of the original image is set as a default.
// retrieve file info
$imginfo = getimagesize($base_img_dir.$tags[\"f\"]);
// load image
switch ($imginfo[2]) {
case 2: // jpg
$img_in = imagecreatefromjpeg($base_img_dir.$tags[\"f\"]) or notfound();
if (!isset($tags[\"t\"])) {
$tags[\"t\"] = \"jpg\";
}
break;
case 3: // png
$img_in = imagecreatefrompng($base_img_dir.$tags[\"f\"]) or notfound();
if (!isset($tags[\"t\"])) {
$tags[\"t\"] = \"png\";
}
break;
default:
notfound();
}
Possible resize
The most important part of the script is, of course, the resize. First, we have to look whether or not a resize is needed. When width or height tags are given, the new width and height are calculated using the size of the original image. The new size is used to copy the original image to the new, resized instance.
// check for maximum width and height
if (isset($tags[\"x\"])) {
if ($tags[\"x\"] < imagesx($img_in)) {
$tags[\"w\"] = $tags[\"x\"];
}
}
if (isset($tags[\"y\"])) {
if ($tags[\"y\"] < imagesy($img_in)) {
$tags[\"h\"] = $tags[\"y\"];
}
}
// check for need to resize
if (isset($tags[\"h\"]) or isset($tags[\"w\"])) {
// convert relative to absolute
if (isset($tags[\"w\"])) {
if (strstr($tags[\"w\"], \"%\")) {
$tags[\"w\"] = (intval(substr($tags[\"w\"],0,-1))/100)*$imginfo[0];
}
}
if (isset($tags[\"h\"])) {
if (strstr($tags[\"h\"], \"%\")) {
$tags[\"h\"] = (intval(substr($tags[\"h\"],0,-1))/100)*$imginfo[1];
}
}
// resize
if (isset($tags[\"w\"]) and isset($tags[\"h\"])) {
$out_w = $tags[\"w\"];
$out_h = $tags[\"h\"];
} elseif (isset($tags[\"w\"]) and !isset($tags[\"h\"])) {
$out_w = $tags[\"w\"];
$out_h = $imginfo[1] * ($tags[\"w\"] / $imginfo[0]);
} elseif (!isset($tags[\"w\"]) and isset($tags[\"h\"])) {
$out_w = $imginfo[0] * ($tags[\"h\"] / $imginfo[1]);
$out_h = $tags[\"h\"];
} else {
$out_w = $tags[\"w\"];
$out_h = $tags[\"h\"];
}
// new image in $img_out
$img_out = imagecreate($out_w, $out_h);
imagecopyresized($img_out,$img_in,0,0,0,0,imagesx($img_out),
imagesy($img_out),imagesx($img_in),imagesy($img_in));
} else {
// no resize needed
$img_out = $img_in;
}
If you\'re using version 2 of the GD-library, you can use imagecreatetruecolor() instead of imagecreate() and imagecopyresampled() instead of imagecopyresampled(). This will get you a much nicer image. (Thanks to Helison Santos, who commented on this.)