18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

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

Chapter 11<br />

Finally we can make the modification to our image:<br />

/**<br />

* Image effect callback; add a text watermark to an image.<br />

*<br />

* @param $image<br />

* An image object returned by image_load().<br />

* @param $data<br />

* An array of attributes to use when performing the<br />

* watermark effect.<br />

* @return<br />

* TRUE on success. FALSE on failure.<br />

*/<br />

function watermark_effect(&$image, $data) {<br />

$data['text_color'] = str_replace('#', '', $data['text_color']);<br />

$red = hexdec(substr($data['text_color'], 0, 2));<br />

$green = hexdec(substr($data['text_color'], 2, 2));<br />

$blue = hexdec(substr($data['text_color'], 4));<br />

}<br />

$color = imagecolorallocate($image->resource, $red, $green, $blue);<br />

imagestring($image->resource, 5, 5, 5, $data['text'], $color);<br />

From a <strong>Drupal</strong> perspective, the important thing is that our effect callback,<br />

watermark_effect(), takes two arguments. The first is an image object just like<br />

we've encountered earlier, which contains a resource handle we can pass to GD<br />

functions for modification. The second is the data array just like the one passed to<br />

our configuration form callback, containing an associative array of user submitted<br />

configuration information. This array is keyed on the field names as specified in the<br />

form callback above. We use the information in $data to properly format our text.<br />

Beyond that this functionality is pretty straightforward. Most of the code is<br />

concerned with properly formatting the color information. In the first four lines we<br />

convert the hex color submitted by the user (found in $data['text_color']) to the<br />

RGB decimal values which we will need later. We do this by parsing each individual<br />

hex value of the string and using hexdec() to convert them to their decimal<br />

equivalent.<br />

The rest of the code relates to the image creation functionality from the GD<br />

image library. We will cover this briefly but for more details refer to the GD<br />

documentation at:<br />

http://in2.php.net/manual/en/book.image.php<br />

[ 337 ]

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

Saved successfully!

Ooh no, something went wrong!