22

I would like to style a text string taken from a form field and then convert it to a transparent .PNG (alpha BG).

Is this possible with PHP? If so, would you kindly show me how this would be achieved

ruhit
  • 221
  • 1
  • 2
  • 6

3 Answers3

29

yes, its very much possible, you are going to follow the same technique as we do while generating a captcha image.

Requirement: GD library should be enabled in your php.

Code (taken from php help file ;)

<?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);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// 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);
?> 
Sourabh Shankar
  • 375
  • 3
  • 8
18

convert text to image (php code):

at first, you need to ensure, that the hosting has enabled GD library (in a new php file, execute phpinfo(); and in output see/find if GD library is enabled) .

Solution 1 (auto-sized output):

TextToImage_my( $text='Helloooo! my unicode words:  ǩ Ƥ Ў  ض ط  Ⴓ ');
    // ==== other parameters can be used too, see the function arguments below

function code: text-to-image.php


Solution 2 (manual-sized output):

(needs to have manual width&height of output, longer strings are cut out)..

<?php
$text = "YOUR  texttttttttttttttt";

$my_img = imagecreate( 200, 80 );                             //width & height
$background  = imagecolorallocate( $my_img, 0,   0,   255 );
$text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 4, 30, 25, $text, $text_colour );
imagesetthickness ( $my_img, 5 );
imageline( $my_img, 30, 45, 165, 45, $line_colour );

header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );
?> 
T.Todua
  • 53,146
  • 19
  • 236
  • 237
0
$image = imagecreate(widthyouwant,heightyouwant);
$bg = imagecolorallocatealpha($image,255,255,255,0);
$black = imagecolorallocate($image,255,255,255);
imagettftext($image,fontsize, 0, x, y, $black, "fontlocation", $_GET['text']);
header('Content-Type: image/png');
imagepng($image);

You could then display the image by going I think thats correct, been awhile since I've done this.

UberMouse
  • 917
  • 2
  • 12
  • 26