Search code examples
phppnggdalpha-transparency

Combines transparent images in one using GD keep transparent


I have a transparent image and a text wider than the image, i am trying to embed the text centered at the top of the transparent image and get a final transparent png image, i have generated the transparent text as a container with the width and height but when combine with the image it comes with a black background

function createImageServer($name, $state)
{
    $path = 'js/FusionCharts/FusionCharts_XT_Website/Charts/Resources/';
    $server = $path . 'server' . $state . '.png';

    list($width, $height, $type, $attr) = getimagesize($server);

    $font_path = 'images_machines/FreeSans.ttf';

    $bbox = imagettfbbox(10,0,$font_path,$name);

    $diffHeight = 5;

    $fontHeight = ($bbox[1] - $bbox[7]) + $diffHeight;
    $textWidth = $bbox[2] + $bbox[0];

    $dstimage = imagecreatetruecolor($textWidth,$height + $fontHeight);
    imagealphablending($dstimage, false);

    //Create alpha channel for transparent layer
    $col=imagecolorallocatealpha($dstimage,255,255,255,127);
    imagefilledrectangle($dstimage,0,0,$textWidth, $height+$fontHeight,$col);
    imagealphablending($dstimage,true);
    imagefttext($dstimage,10,0,0,$fontHeight-$diffHeight,0,$font_path,$name);


    $srcimage = imagecreatefrompng($server);
    imagealphablending($srcimage, false);

    imagecopymerge($dstimage,$srcimage,($textWidth/2)-($width/2),$fontHeight,0,0,$width,$height,100);
    imagealphablending($dstimage, true);
    imagesavealpha($dstimage, true);

    $pathImage = 'images_machines/' . $name . '.png';


    imagepng($dstimage,$pathImage);

    imagedestroy($dstimage);
    imagedestroy($srcimage);

    return $pathImage;
}

Original image:

enter image description here

Resulting image:

enter image description here


Solution

  • Replace your call to imagecopymerge with imagecopy (change the function name and remove the last parameter):

    //imagecopymerge($dstimage,$srcimage,($textWidth/2)-($width/2),$fontHeight,0,0,$width,$height,100);
    
    imagecopy($dstimage,$srcimage,($textWidth/2)-($width/2),$fontHeight,0,0,$width,$height);
    

    Result:

    enter image description here