Search code examples
phpimagejpeg

PHP imagejpeg not displaying image on Browser


I am using imagejpg() to display an image on the browser and place text over the image.

I have used this before and it has worked. Now I switched domain hosts and perhaps the PHP version is different as the image is now not displaying.

It displays a small square in the middle of the screen, like a broken link, but the image is definitely there.

Could someone please assist with this?

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

// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('images1/new_image.jpg');

// Allocate A Color For The Text
$red = imagecolorallocate($jpg_image, 255, 0, 0);
$green = imagecolorallocate($jpg_image, 0, 255, 0);

// Set Path to Font File
$font_path = 'canadian.ttf';

$text1 = "hello";
$text2 = "there";
$text3 = "world";

//Floor 17
  imagettftext($jpg_image, 12, 0, 272, 17, $green, $font_path, $text1);
  imagettftext($jpg_image, 12, 0, 200, 38, $green, $font_path, $text2);
  imagettftext($jpg_image, 12, 0, 480, 17, $green, $font_path, $text3);

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

  // Clear Memory
  imagedestroy($jpg_image);

Thank you in advance.

Rob


Solution

  • I just figured it out. Answer below

    I moved the header down and it sorted out the problem.

    // Create Image From Existing File
    $jpg_image = imagecreatefromjpeg('images1/new_image.jpg');
    
    // Allocate A Color For The Text
    $red = imagecolorallocate($jpg_image, 255, 0, 0);
    $green = imagecolorallocate($jpg_image, 0, 255, 0);
    
    // Set Path to Font File
    $font_path = 'canadian.ttf';
    
    $text1 = "hello";
    $text2 = "there";
    $text3 = "world";
    
    //Floor 17
      imagettftext($jpg_image, 12, 0, 272, 17, $green, $font_path, $text1);
      imagettftext($jpg_image, 12, 0, 200, 38, $green, $font_path, $text2);
      imagettftext($jpg_image, 12, 0, 480, 17, $green, $font_path, $text3);
    
      header('Content-type: image/jpeg');
    
      // Send Image to Browser
      imagejpeg($jpg_image);
    
      // Clear Memory
      imagedestroy($jpg_image);