Search code examples
phpimagegdwampserverimagettftext

PHP imagettftext() breaks the image if I use imagecreatefrompng, imagecreatefromjpeg and imagecreatefromgif


The image get loaded to the browser fine but when I try writing some text onto it, the image breaks (like this: http://www.tradenepal.com.np/test.php ). When I comment out imagettftext(), the image does not load again. This happening on my localhost and I use WampServer Version 2.5. I have gone through so many comments on the inetrnet but I can't seem to know what the problem is. Any help would much be appreciated. Thank you. My code:

<?php 

//Set content type
header('Content-type: image/jpeg');

// Create image from existing image
$jpgImage = imagecreatefromjpeg('file.jpg');

// Allocate color for text
$white = imagecolorallocate($jpgImage, 255, 255, 255);

// Set Path to Font File
$font = 'arialbd.ttf';

// Text to print to image
$text = 'Testing text output';

// Print Text On Image
imagettftext($jpgImage, 75, 0, 50, 400, $white, $font, $text);



// Send Image to Browser
imagejpeg($jpgImage);

// Clear Memory
imagedestroy($jpgImage);

?> 

Solution

  • // Send Image to Browser

    imagepng($jpg_image);  <------ remove image type png
    

    // Output the image

    imagejpeg($jpg_image);
    

    I've tested, it works.

    <?php
      //Set the Content Type
      header('Content-type: image/jpeg');
    
      // Create Image From Existing File
      $jpg_image = imagecreatefromjpeg('file.jpg');
    
      // Allocate A Color For The Text
      $white = imagecolorallocate($jpg_image, 255, 255, 255);
    
      // Set Path to Font File
      $font_path = 'arialbd.ttf';
    
      // Set Text to Be Printed On Image
      $text = "This is a sunset!";
    
      // Print Text On Image
      imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);
    
      // Send Image to Browser
      imagejpeg($jpg_image);
    
      // Clear Memory
      imagedestroy($jpg_image);
    ?>