Search code examples
phpphp-gdimagettftext

PHP imagettftext() Font Letters Not Transparent


I am using the PHP GD library to allow users to generate their name on top of a background image that I supply. The current issue is that the letters in the outputted PNG are not transparent--as you can see below they overlap each other.

Text: Roger Ajax

Background Image:

Background Image

Result:

Non Transparent Letters

Could this perhaps be due to the TTF font? I have tried the following fonts with the same result:

- HomemadeApple.ttf
- IndieFlower.ttf 
- DancingScript.ttf 
- KaushanScript Regular.ttf
- PermanentMarker.ttf

Here is the full source of my function:

    $signature_text = "Roger Ajax";
    $font_name = "Homemade Apple";

    // Lowercase all letters then capitalize First Lettter of each word
    $signature_text = strtolower($signature_text);
    $signature_text = ucwords($signature_text);

    // Font & Text Settings
    $font_size = 32;
    $font = "/var/gosigner/fonts/HomemadeApple.ttf";
    $desired_width = strlen($signature_text) * 34;
    $start_position = 32;

    // Background Image
    $originalImage = $this->config->item('app_root') . "img/signature_field_blank.png";

    // Verify BG Image can be found
    if(!file_exists($originalImage)) {
        $this->shared->throw_error("Signature template file could not be found");
    }

    $im = imagecreatefrompng($originalImage); // Get original
    imagealphablending($im, false);           // Save Transparency
    imagesavealpha($im, true);                // Save Transparencyc

    $img_resized = imagecreatetruecolor($desired_width, 72);   // Create new PNG
    imagealphablending($img_resized, false);                   // Save Transparency
    imagesavealpha($img_resized, true);    

    $trans_colour = imagecolorallocatealpha($img_resized, 0, 0, 0, 127);
    imagefill($img_resized, 0, 0, $trans_colour);


    $x = imagesx($im); // Original X
    $y = imagesy($im); // Original Y
    imagecopyresampled($img_resized, $im, 0, 0, 0, 0, 214, 72, $x, $y);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagettftext($img_resized, $font_size, 0, $start_position, 45, $black, $font, $signature_text);

    header('Content-Type: image/png');
    imagepng($img_resized);
    imagedestroy($im);
    imagedestroy($img_resized);

Solution

  • I'd add the text to $img_resized (here I'm using different font & color)

    Roger Ajax

    $img_resized = imagecreatetruecolor($desired_width, 72);
    imagesavealpha($img_resized, true);
    imagefill($img_resized, 0, 0, IMG_COLOR_TRANSPARENT);
    $black = imagecolorallocate($img_resized, 0, 0, 0);
    imagefttext($img_resized, $font_size, 0, $start_position, 45, $black, $font, $signature_text);
    

    before placing it on top of $im.

    imagecopyresampled($img_resized, $im, 0, 0, 0, 0, 214, 72, $x, $y);
    

    (in addition I'm not using the imagealphablending() part and using IMG_COLOR_TRANSPARENT instead of $trans_colour)