13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Using Text <strong>and</strong> Fonts to Create Images<br />

495<br />

Setting Up the Base Canvas<br />

In Listing 22.2, instead of starting from scratch, you start with an existing image for the<br />

button.You provide a choice of three colors in the basic button: red (red-button.png),<br />

green (green-button.png), <strong>and</strong> blue (blue-button.png).<br />

The user’s chosen color is stored in the color variable from the form.<br />

You begin by extracting the color from the superglobal $_REQUEST <strong>and</strong> setting up a<br />

new image identifier based on the appropriate button:<br />

$color = $_REQUEST[‘color’];<br />

...<br />

$im = imagecreatefrompng ($color.’-button.png’);<br />

The function imagecreatefrompng() takes the filename of a PNG as a parameter <strong>and</strong><br />

returns a new image identifier for an image containing a copy of that PNG. Note that<br />

this does not modify the base PNG in any way.You can use the imagecreatefromjpeg()<br />

<strong>and</strong> imagecreatefromgif() functions in the same way if the appropriate<br />

support is installed.<br />

Note<br />

The call to imagecreatefrompng() creates the image in memory only. To save the image to a file or<br />

output it to the browser, you must call the imagepng() function. You’ll come to that discussion shortly,<br />

but you have other work to do with the image first.<br />

Fitting the Text onto the Button<br />

Some text typed in by the user is stored in the $button_text variable.What you need<br />

to do is print that text on the button in the largest font size that will fit.You do this by<br />

iteration, or strictly speaking, by iterative trial <strong>and</strong> error.<br />

You start by setting up some relevant variables.The first two are the height <strong>and</strong> width<br />

of the button image:<br />

$width_image = imagesx($im);<br />

$height_image = imagesy($im);<br />

The second two represent a margin in from the edge of the button.The button images<br />

are beveled, so you need to leave room for that around the edges of the text. If you are<br />

using different images, this number will be different! In this case, the margin on each<br />

side is around 18 pixels:<br />

$width_image_wo_margins = $width_image - (2 * 18);<br />

$height_image_wo_margins = $height_image - (2 * 18);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!