Manipulating images is a tool that more and more web programmers are having to add to their repertoire due to the growth of Web 2.0 and the requirement to make sites more social with thumbnails, avatars and so on.
Websites for freelancers, for example, often need to support image uploads of photos of the freelancers themselves as well as of their work. Likewise auction, classifieds and other sites that sell products on behalf of the surfer need a way to accept an upload of the products for sale.
But it’s not sufficient to simply support http file upload, because images will be posted to you of all sizes and dimensions. Many of the latest digital cameras offer in excess of ten megapixels and the default file sizes are very high resolution (thousands by thousands of pixels) and take up several megabytes of space.
Therefore you need to be able to take uploaded images and resize them to suitable dimensions for the website in question, and also save them in the file format of your choice. Along the way you may well need to either offer your users the opportunity to adjust the final image, or automatically do so yourself. This is particularly necessary when you have resized an image down substantially to a thumbnail, as you will almost certainly have to sharpen it.
Before you start, though, you must ensure that your web (or development) server has the GD Lib compiled into PHP as that is the only way these functions will work.
For the purposes of this article I have limited the supported file types to GIF, PNG and JPG. In practice you will probably find these three are sufficient for most purposes anyway.
The following code snippet is the first part of the complete program file which should be saved as
picproc.php. It contains the opening code to tell the web server to process PHP, and then the main html used by the program is output: