After several try to make a graphical submit form button with localizable text in it i found it’s not so simple. Furthermore there are no cases I found in the Internet. This mean weather I hav to create an image button for each language or… here is the story how I made this.
Problem definition
As input we have a button background layout and a text string to draw on the button background.
As output we should have an URL wich produces button with text.
Right now caching of result images is not important, but we can add it later for high performance aplications.
The solution
We use php GD library to load image, and draw a text on it. After the image is ready it’s writen to the webserver response stream.
To draw a text we need a font, the arial.ttf will fit, so we place it in to the /app/vendors/imagetext/arial.ttf to use it later in our controller.
To output image we create controller and remove any model associations from it (we do not need model for that functionality, the image name and text to draw we need we will get from parameters).
Here is the controller code:
<?php /** * Controller provides functionality to render imges with specified text over it */ class ImagesController extends Controller { var $uses = array(); /** * Diaplays image with text over it */ function textover($caption, $image) { // Some basic setup $textFont = realpath(VENDORS.'imagetext').'/'.'arial'.'.ttf'; $textSize = 15; $textString = $caption; $imageFile = IMAGES_URL.DS.$image; // Load background image $image = imagecreatefrompng($imageFile); $textColor = imagecolorallocate($image, 0, 0, 0); //Get image dimensions list($imageWidth, $imageHeight) = getimagesize($imageFile); // Get box info $box = imagettfbbox($textSize, 0, $textFont, $textString); //Find out the width and height of the text box $textW = $box[2] - $box[0]; $textH = $box[5] - $box[3]; // Calculate the positions $positionLeft = ($imageWidth - $textW)/2; $positionTop = (($imageHeight - $textH)/2); // Add some text imagettftext($image, $textSize, 0, $positionLeft, $positionTop, $textColor, $textFont, $textString); header('Pragma: public'); header('Content-type: image/png'); imagepng($image); // Destroy the image imagedestroy($image); $this->autoRender=false; } } ?>
That’s it. Now we are ready to get our image from the url /images/textover/[caption]/[background].png
where the caption is the text to draw on the image and the bacground.png is a filename in the /app/webroot/img directory. Try to get image by that url, if it works ok then you can use it as a source of input.
<input type="image" src="/images/textover/Submit/mybutton.png"/>