Search code examples
phpmergegdimagettftext

merge 3 images and add a text in PHP


I managed to merge 3 images in PHP with this code:

header ("Content-type: image/jpeg"); 

$image1Url = "1.jpg"; 
$image2Url = "2t.jpg"; 
$image3Url = "3.jpg"; 
$image1 = imageCreateFromjpeg($image1Url); 
$image2 = imageCreateFromjpeg($image2Url); 
$image3 = imageCreateFromjpeg($image3Url); 

$colorTransparent = imagecolorat($image1, 0, 0); 
$colorTransparent = imagecolorat($image2, 0, 0); 
$colorTransparent = imagecolorat($image3, 0, 0); 


imagecopymerge($image1, $image2, 20, 9, 0, 0, 240, 240, 100); 
imageCopyMerge($image1, $image3, 200, 10, 0, 0, 60, 40, 100); 

Imagejpeg ($image1); 


ImageDestroy ($image1); 
ImageDestroy ($image2);

I now want to add some text, so my final code is:

header ("Content-type: image/jpeg"); 

$image1Url = "1.jpg"; 
$image2Url = "2.jpg"; 
$image3Url = "3.jpg"; 
$image1 = imageCreateFromjpeg($image1Url); 
$image2 = imageCreateFromjpeg($image2Url); 
$image3 = imageCreateFromjpeg($image3Url); 

$colorTransparent = imagecolorat($image1, 0, 0); 
$colorTransparent = imagecolorat($image2, 0, 0); 
$colorTransparent = imagecolorat($image3, 0, 0); 


imagecopymerge($image1, $image2, 20, 9, 0, 0, 240, 240, 100);
imageCopyMerge($image1, $image3, 200, 10, 0, 0, 60, 40, 100); 
$text = "Username";
$font = "Font.ttf";
$black = imagecolorallocate($im, 0, 0, 0);

imagettftext($image1, 10, 0, 217, 15, $black, $font, $text);
Imagejpeg ($image1); 


ImageDestroy ($image1); 
ImageDestroy ($image2);

But the image is not displaying


Solution

  • I think the problem is in this line:

    $black = imagecolorallocate($im, 0, 0, 0);
    

    Var $im doesn't exists so I'd suggest you to change $im for $image1.

    Im assuming that Font.ttf is reachable.