没有显示文字,只有验证码线可见

PHP code:

<?php 
ob_start();
session_start();
$_SESSION['secure'];
header('content-type:image/png');
$text="hello";
$font_size=25;
$width=200;
$height=200;
$image=imagecreate($width, $height);
imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
for($x=1; $x <= 30; $x++) {
    $x1 = rand(1, 100);
    $y1 = rand(1, 100);
    $x2 = rand(1, 100);
    $y2 = rand(1, 100);
    imageline($image, $x1, $y1, $x2, $y2, $black);
}
imagettftext($image, $font_size, 0, 15, 30, $black, 'consolas.ttf', $text);
$imgSrc="out.png";
imagejpeg($image, $imgSrc);
?>

When the image is generated, only lines are drawn but text("hello") is not drawn on it. The font is also in the same directory, I have also kept it in another directory and added the complete path no luck.

I'm debugging this issue and found that font file is not accessible.

I have checked by turning on debugging as below:

error_reporting(E_ALL);
ini_set("display_errors", 1);

And commented lines below.

header('content-type:image/png');


imagepng($image);

Got error:

Warning: imagettftext(): Could not find/open font in /var/www/html/index.php on line 24

Soultion:

Path to font file should be realpath on server. So the code should be:

imagettftext($image, $font_size, 0, 15, 30, $black, realpath('consolas.ttf'), $text);

Also change in render image without giving $imgSrc and changing it to

imagepng($image);

instead of

$imgSrc="out.png";
imagejpeg($image, $imgSrc);

Finally complete code will look like:

ob_start();
session_start();
$_SESSION['secure'];
header('content-type:image/png');
$text = "hello";
$font_size = 25;
$width = 200;
$height = 200;
$image = imagecreate($width, $height);
imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
for ($x = 1; $x <= 30; $x++) {
    $x1 = rand(1, 100);
    $y1 = rand(1, 100);
    $x2 = rand(1, 100);
    $y2 = rand(1, 100);
    imageline($image, $x1, $y1, $x2, $y2, $black);
}
imagettftext($image, $font_size, 0, 15, 30, $black, realpath('Consolas.ttf'), $text);
imagepng($image);