imagettftext - Center align text same way CSS does it - php

I've seen so many demos on how to have the text aligned in the center of an image, but I am looking to have the text center aligned so that it appears the same as CSS text-align:centeror photoshop's center align.
How can I achieve this with imagettftext?
This is my code so far:
$new_image = imagecreatefromjpeg(get_template_directory()."/images/homepage/blackboard.jpg"); // Load up the blackboard image.
$white = imagecolorallocate($new_image, 255, 255, 255); // Create a white colour
$font_path = get_template_directory()."/fonts/PermanentMarker.ttf"; // Set font
$text = get_field("blackboard_message", $page->ID); // Create text object
$text_length = 19;
$text = wordwrap($text, $text_length, "\n", true);
imagettftext($new_image, 16, 0, 60, 185, $white, $font_path, $text); // Add text to image.
$mask = imagecreatefrompng(get_template_directory()."/images/homepage/blackboard-mask.png"); // Load the mask
imagesavealpha($mask, false); // Do not save full alpha channels
imagealphablending($mask, false); // Disable alpha blending
imagecopy($new_image, $mask, 55, 160, 0, 0, 224, 285); // Copy mask on top of blackboard image.
imagejpeg($new_image, get_template_directory()."/images/homepage/blackboard/blackboard-message-$modified_unix_timestamp.jpg");
The end result should look like this:

Related

GD bounding box incorrect for text (php)

I'm having issues with text lining up where it should. Every tutorial I can find tells me to use imagettfbox to find the dimensions of the text. I do this, but the text doesn't fit within those dimensions.
See the example below:
<?php
// Create image and colours
$im = imagecreatetruecolor(200, 100);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
$red = imagecolorallocate($im, 255, 0, 0);
//Set the background to be white
imagefilledrectangle($im, 0, 0, 200, 100, $white);
//font file
$font = "ARIAL.TTF";
//set sample text and fontsize
$text="102";
$size = 25;
//calculate height and width of text1
$bbox = imagettfbbox($size, 0, $font, $text);
$width = $bbox[2] - $bbox[0];
$height = $bbox[5] - $bbox[3];
//draw rectangle that should house the text
imagefilledrectangle($im, 50, 40, 50+$width, 40+$height, $red);
//draw text at same startpoint as rectangle
imagettftext($im, $size, 0, 50, 40, $black, $font, $text);
// Output to browser
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
This should output a red rectangle, containing the text. It doesn't - the text is slightly to the right of where it should be. This only happens with some strings - ones that contain a "1" tend not to work, while some others work perfectly. Here is the output for 2 strings:
Does anyone know what is happening, and what I need to do to make the text fit correctly within the bounding box? I've tested this with multiple fonts, including monospace fonts - the same thing always happens.

How to join Urdu alphabets while converting text into image in PHP

I use TIC to convert text into images.
I have searched a lot on this but it seems like Unicode problem (unicodes of initial medial and final letters) or may be content type as image is in PNG.
If I echo without image conversion with content type text/html and charset=UTF-8 I get the desired output with join Urdu letters.
require_once 'lib/tic.php';
$text="زہرہ نور ";
TIC::factory('C:\Windows\Fonts\Nastalique.ttf')
->setText($text)
->setPadding(10)
->setBgColor('ff0000')
->setFontColor(0xff, 0xff, 0x00)
->setFontSize(24)->create(true);
Getting out put as
ز ہ ر ہ ن و ر
You may do it like this:
$text = "زہرہ نور";
// Make it RTL
preg_match_all('/([^\d]|\d+)/us', $text, $ar);
$text = join('',array_reverse($ar[0]));
// Set font
$font = 'C:\Windows\Fonts\Nastalique.ttf';
// Create the image
$im = imagecreatetruecolor(160, 160);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
// Create some colors
imagefilledrectangle($im, 0, 0, 159, 159, $white);
// Set the headers
header('Content-type: image/gif');
// Add the text
imagettftext($im, 12, 0, 20, 20, $black, $font, $text);
imagegif($im);
imagedestroy($im);
If did not work for you, you have the option to use php-gd-farsi.
How to use
Just copy the library to your PHP directory. The usage is simple:
include('php-gd-farsi-master/FarsiGD.php');
$gd = new FarsiGD();
....
// then convert your text:
$tx = $gd->persianText($str, 'fa', 'normal');
Complete code
include('php-gd-farsi-master/FarsiGD.php');
$gd = new FarsiGD();
// Create a 300x100 image
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);
// Make the background red
imagefilledrectangle($im, 0, 0, 299, 99, $red);
// Path to our ttf font file
$font_file = './Nastalique.ttf';
// Draw the text 'PHP Manual' using font size 13
$text = imagecreatetruecolor(200, 60);
imagefilledrectangle($text, 0, 0, 200, 60, $red);
$str = 'زہرہ نور';
$tx = $gd->persianText($str, 'fa', 'normal');
imagefttext($text, 24, 10, 10, 50, $black, $font_file,$tx );
$im = $text;
// Output image to the browser
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

How to write text to images with different sizes using PHP GD

I'm creating images with different sizes. How can I write text on those images so that the texts always fit to the images?
$text = "some text as example";
$font = "arialbd.ttf"
$fontsize = 26;
offset_x = 0;
offset_y = 0;
$image01 = imagecreate( 1120 , 900 );
$image02 = imagecreate( 400 , 300 );
$image03 = imagecreate( 1120 , 900 );
I know that there is the imagefttext function that can apply text to the images but with that function I can only change the font size to make the text bigger. How can I find out that it fits into my image?
If you are looking to scale the font size so that text string fills the image width, try this.
Using imagettfbbox, determine the current text box width:
$bbox = imagettfbbox($fontsize,0,$fontpath,$string);
$tbwidth = $bbox[2];
Then divide the image width by the $tbwidth to get a factor
$factor = round(($imgwidth / $tbwidth), 0, PHP_ROUND_HALF_DOWN); //ie. 800/240=3
Multiple the $factor by you $fontsize to get an approximate increase.
$newfontsize = $fontsize * $factor; //ie. 12(pt) * 3 = 36
Keep in minds, if you're using GD 2.0, fontsize is in Points and not pixels. Your algorithm is going to calculate the difference between your default font size text box (expressed as a text box width) and the image width.
// Set the content-type
header('Content-Type: image/png');
// Create the image
$im = imagecreatetruecolor(800, 600);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 0, 0, $white);
// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font_file = 'arial.ttf';
$font_size = '15';
$bbox = imageftbbox($font_size, 0, $font_file, $text);
$width = $bbox[2] - $bbox[6];
$height = $bbox[3] - $bbox[7];
// Add the text
imagettftext($im, $font_size, 0, 10, 20, $black, $font_file, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
I recently came across the same situation with transparent backgrounds but the current examples are either not a solution but clues or a solution that doesn't work, so hereby a combined and working solution if anyone need it.
function imagecreater($width = 600, $height = 600) {
//Create an empty transparent image
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, false);
imagesavealpha($img, true);
$transparent = imagecolorallocatealpha($img, 255, 255, 255, 127);
imagefill($img, 0, 0, $transparent);
//Text information
$text = "some text as example";
$font = "arialbd.ttf"
$fontsize = 26; //default font to be altered later
//simulate a complete text box and get the width
$bbox = imageftbbox($fontsize, 0, $font, $text);
$tbwidth = $bbox[2];
//Calculate different between our transparent image and text box
//I've added a little padding (20px) since the text sometimes crossing the edge..
$factor = (($width - 20) / $tbwidth);
//Alter font size with difference to fit fully image
$newfontsize = $fontsize * $factor;
//Find the horisontal center
$bbox = imageftbbox($newfontsize, 0, $font, $text);
$newheight = ($height / 2) + (($bbox[3] - $bbox[7]) / 2);
//Set Color of text
$color = imagecolorallocate($img, 200, 0, 0);
//Produce our image
imagettftext($img, $newfontsize, 0, 0, $newheight, $color, $font, $text);
//Copy image to file and free the cached image
$target = "testimage.png";
imagepng($img, $target);
imagedestroy($img);
}
As rwhite35 mentioning here, please keep in mind that GD 2.0 write font size is in points and not pixels.
Use the imageftbbox function to get the size of the bounding box of the text. You can then adjust the text size to fit the size of the image exactly.
http://www.php.net/manual/en/function.imageftbbox.php

Create White Box around Text GD-Lib

i want to add a white box around some text i add to an image via GD-Lib.
but i don't know how to do this best.
Here is my current code:
<?php
$textImg = imagecreatefromjpeg($tempImage);
$black = imagecolorallocate($textImg, 0, 0, 0);
$font = 'lib/verdana.ttf';
// Add the text
imagettftext($textImg, 20, 0, imagesx($textImg)*$textData['x']/100, imagesy($textImg)*$textData['y']/100, $black, $font, $textData['text']);
imagejpeg($textImg,$tempImage,$jpegQuality);
?>
I hope you can help me out.
You can use imagettfbbox() to get the coordinates of the bounding box by passing the same settings you use for the text itself (same text, font and size etc).
Once you have these coordinates you can use imagerectangle() to draw a border around the text, or you can use imagefilledrectangle() to draw a solid rectangle. Be sure to call it before you render the text with imagettftext()
A basic example is below but will need some tweaking as most of it is from memory and I suspect the $x and $y calculation could be done better as it probably doesn't work with varying canvas sizes as it is now. However, it demonstrates the principle.
// Set the content-type
header('Content-Type: image/png');
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $black);
// The text to draw
$text = 'Testing';
// Replace path by your own font path
$font = 'verdana.ttf';
// Add the text
$bbox = imagettfbbox(20, 0, $font, $text);
$x = $bbox[1] + (imagesx($im) / 2) - ($bbox[4]);
$y = $bbox[3] + (imagesy($im) / 2) - ($bbox[5]);
imagerectangle($im, 0, 0, $x, $y, $white);
imagettftext($im, 20, 0, 0, 20, $white, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagejpeg($im);
imagedestroy($im);

Outputting image with underlined text using php GD library

What is the best way to display underlined text and output the result as image with GD or any other library?
You can try using the Unicode underline combining character U+0332.
<?php
// Set the content-type
header('Content-type: image/png');
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw
$text = "̲U̲d̲e̲r̲l̲i̲n̲e";
// Replace path by your own font path
$font = 'arial.ttf';
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
There are lots of FREE PHP CAPTCHA out there that come with a lot of customization, download one and see what exactly happens behind the scene. Also have a look at this link
HTH
I am using this...
$font = imageloadfont($font_file);
$font_width = ImageFontWidth($font);
$font_height = ImageFontHeight($font);
$str_width = strlen($text)*$font_width;
ImageLine($image, $left, $top+$font_height, $left+$str_width, $top+$font_height, $color);

Categories