For developers like Divyesh, one of the most popular features of PHP is real-time image generation. That is, we can create a new image canvas, "paint" it, and either save it to a file, or send it directly to the browser. In this article, Divyesh will show you how to create an image in real-time with PHP.
Generating Images on the Fly With PHP - Creating our image (Page 3 of 7 )
The first step to creating our image is to create a canvas to work with. We do this by using the imagecreate function, as shown below:
$img_number = imagecreate(100, 50);
The imagecreate function creates a blank canvas. The width and height of the canvas are determined by the two parameters passed to the function respectively. So, in our example above, we have created a new image that is 100 pixels wide, by 50 pixels high.
The next step is to allocate the colours that will be used to generate our random number image. We use the imagecolorallocate function to do this. The imagecolorallocate function takes four arguments. The first is the image identifier, which in our case is $img_number. The last three arguments specify the RGB values of the colour that we are creating. RGB (red, green and blue) values range from 0 (the darkest) to 255 (the lightest). For example, black is 0, 0, 0 and white is 255, 255, 255. Letís create a couple of colours:
The imagefill function performs a complete fill of the canvas identified by the first argument, $img_number. Arguments two and three specify the x and y co-ordinates to start filling from. The last parameter is a variable created using the imagecolorallocate function.
Next, we draw two rectangles using the ImageRectangle function. The first argument to the ImageRectangle is a reference to a drawing canvas created using the imagecreate function. The next four arguments specify the top left-hand corner of the rectangle, as well as the lower right-hand corner. The last parameter is a reference to a colour, created using the imagecolorallocate function.
In our example, we have created a new image canvas, filled our canvas, and added some rectangles, but where is the image you might ask? Good question. At this point in time, our image is still stored in memory. Itís really quite easy to display the image in a web browser, so letís do that now!