In a previous post (how to draw a string into an image with php) I explained how to draw a string on a opaque background image.

This time I want to add transparency to both background and text layers.

Three functions help us to do the work:

  1. imagealphablending — Set the blending mode for an image
  2. imagecolorallocatealpha — Allocate a color for an image with the addition of the transparency parameter alpha.
  3. imagesavealpha — Set the flag to save full alpha channel information (as opposed to single-color transparency) when saving PNG images

The source code is very simple and it's also very similar to the one of the previous post:

#!/usr/bin/php

<?php

    // Create the image

    $image = imagecreatetruecolor(800, 600);

    imagealphablending($image, false);

    

    //Create alpha channel for transparent layer

    $col=imagecolorallocatealpha($image,120,255,255,127);

    

    //Create alpha channel for transparent layer

    $grey=imagecolorallocatealpha($image, 130, 255, 255, 80);

    

    //Create overlapping 800×600 transparent layer

    imagefilledrectangle($image, 0, 0, 800, 600,$col);

    

    //Continue to keep layers transparent

    imagealphablending($image,true);

    

    // The text to draw

    $text1 = $argv[1];

    $text2 = $argv[2];

    $text  = $argv[1]."\n".$argv[2];

    

    // Replace path by your own font path

    $font = '/Library/Fonts/Apple Chancery.ttf';

    

    // Add the text

    imagettftext($image, 48, 0, 20, 320, $grey, $font, $text);

    

    //Keep trnsparent when saving

    imagesavealpha($image,true);

    

    //Save & output

    imagepng($image, "simpleimage.png", 1);

    imagedestroy($image);

?>

 

Save as drawstring.php the above script, then issue the following command to make the script runnable:


 
run the script issueing the following command:

You should obtain something like the following image:

php draw translucent string

Now you can play with colors to obtain something better

Gg1