Returning the image
The last step in our script is the actual returning of the image. The image and corresponding headers are returned as set in the query string. If the wanted type is not given, the image is returned as the original type of the saved file.
// check for a given jpeg-quality, otherwise set to default
if (!isset($tags[\"q\"])) {
$tags[\"q\"] = 75;
}
// returning the image
switch ($tags[\"t\"]) {
case \"jpg\":
header(\"Content-type: image/jpeg\");
imagejpeg($img_out, \"\", $tags[\"q\"]);
exit;
case \"png\":
header(\"Content-type: image/png\");
imagepng($img_out);
exit;
default:
notfound();
}
What We Did
Now we have a script that fulfils the tasks we described above. Images are uploaded once and can be resized to whatever you want, without manual action. For the editors, the users of your CMS, uploading images is very simple. They upload the file in the size and type they want, and the script takes care of the resizing and converting. Without more work, your site can show thumbnails in many different sizes. If you, in the near future, would like to redesign your site, it is easy to get a new image size, without having to resize your whole archive.
The complete script discussed above, is available for download here. A demo of the script is running here, change the arguments in the query string to try the different commands like w() and t().
Where to go from here
Some thoughts about possible extensions of this script:
Enabling GIF-output. Using the command-line pngtopnm and pmmtogif programs, you can convert PNG-images to GIF on the fly. That way, you do not have to worry about older browsers not supporting the PNG-format.
Uploading of files in more formats. For the users of your CMS, it would be very easy if they could upload images as GIF, Windows bitmaps and TIFF. Using open source conversion utilities, you can still save these images as PNG of JPEG after uploading.
Using normal filenames for the images. Filenames generated with uniqid(); are easy and unique, but not very descriptive.
Saving file information like default ALT-tags in a database. You can easily find images for use in articles.