As with all things in life, we have to learn to walk before we can run – before we can jump in and start producing the goods, we have a few basics to get through. PHP uses the gd graphics library for all but its most basic image functions. Provided you have a recent version of the library, you can create and manipulate images in a number of different formats; the two most noteworthy are JPEG and PNG. These are both compressed file formats, which means that they use mathematical algorithms to reduce the amount of data required to completely describe the image. They therefore play a very important role in keeping your file sizes small and download times short!
It's important to be able to recognize where you should use each format – they use quite different compression techniques, and most images will be better suited to one or the other.
The JPEG format uses lossy compression. What this means is that some of the data in the original image is lost during compression. The format is designed to work best with images like photographs (that's where the "P" in "JPEG" comes from), where there's a lot of subtle shading and not too much fine detail. It's the format to use when a slight loss in quality won't be too apparent to the viewer.
The PNG format on the other hand is compressed in a lossless fashion. It works best with images that contain lines and large blocks of color, cartoons for example. When the image is uncompressed, it will contain all of its original information. This means that sharp edges and straight lines (which suffer under JPEG compression) will be reproduced faithfully.
Early versions of gd (and thus PHP) contained support for GIF files, which are similar in many respects to PNG. However, Unisys holds a patent on the LZW compression algorithm used to create fully compressed GIFs, and consequently GIF support has been completely replaced by that for PNG files since gd version 1.6. All is far from lost though, as JPEG and the excellent PNG image encoding formats should be sufficient for all your graphics needs. Before we even look at the technicalities of creating the image, let's go through the steps involved in getting PHP to create an image and display it in the browser:
This is effectively just a section of memory in which we define an image before outputting it to the browser or to disk.
Create an image canvas for PHP to work on – this is simply a reserved portion of server memory, onto which the script will "draw" (that is, write data) before outputting it to the browser or disk as an image.
Draw the picture on the image canvas.
Send the image to the browser.
Clean up memory by throwing away the image canvas.