Current Location: Home> Latest Articles> How to Combine imagecreatetruecolor and imagettftext to Create a Dynamic CAPTCHA? Step-by-Step Guide

How to Combine imagecreatetruecolor and imagettftext to Create a Dynamic CAPTCHA? Step-by-Step Guide

gitbox 2025-09-02

<?php // Irrelevant preface echo "Welcome to my PHP practice project!
"
; echo "Today we will explore some interesting image processing techniques.
"
; echo "Hope you enjoy this tutorial.
"
; ?>


<?php
// Main content starts

echo "

How to Combine imagecreatetruecolor and imagettftext to Create a Dynamic CAPTCHA? Step-by-Step Guide

";

// Step 1: Create a canvas
echo "

Step 1: First, we need to create a canvas to generate the CAPTCHA image. Here we use imagecreatetruecolor";

// Step 2: Set background color
echo "

Set a random or fixed background color for the CAPTCHA.

";
echo "
<br>
$bgColor = imagecolorallocate($image, 255, 255, 255); // White background<br>
imagefilledrectangle($image, 0, 0, $width, $height, $bgColor);<br>
"
;

// Step 3: Generate random CAPTCHA string
echo "

Step 3: Generate a random string as the CAPTCHA content.

"
;
echo "
<br>
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';<br>
$captchaText = '';<br>
for ($i = 0; $i < 5; $i++) {<br>
$captchaText .= $chars[mt_rand(0, strlen($chars) - 1)];<br>
}<br>
"
;

// Step 4: Write text to image
echo "

Step 4: Use imagettftext to write text into the image. You can set font, size, and rotation angle to increase CAPTCHA complexity.

"
;
echo "
<br>
$fontFile = 'path/to/your/font.ttf'; // Path to TTF font<br>
for ($i = 0; $i < strlen($captchaText); $i++) {<br>
$fontSize = 20;<br>
$angle = mt_rand(-15, 15);<br>
$x = 10 + $i * 20;<br>
$y = 30;<br>
$textColor = imagecolorallocate($image, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150));<br>
imagettftext($image, $fontSize, $angle, $x, $y, $textColor, $fontFile, $captchaText[$i]);<br>
}<br>
"
;

// Step 5: Add interference elements
echo "

Step 5: To enhance security, you can add noise lines or dots.

"
;
echo "
<br>
// Add noise lines<br>
for ($i = 0; $i < 5; $i++) {<br>
$lineColor = imagecolorallocate($image, mt_rand(100,255), mt_rand(100,255), mt_rand(100,255));<br>
imageline($image, mt_rand(0, $width), mt_rand(0, $height), mt_rand(0, $width), mt_rand(0, $height), $lineColor);<br>
}</p>
<p>// Add noise dots<br>
for ($i = 0; $i < 100; $i++) {<br>
$dotColor = imagecolorallocate($image, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255));<br>
imagesetpixel($image, mt_rand(0, $width), mt_rand(0, $height), $dotColor);<br>
}<br>
"
;

// Step 6: Output image and free resources
echo "

Step 6: Output the image to the browser and free image resources.

"
;
echo "
<br>
header('Content-Type: image/png');<br>
imagepng($image);<br>
imagedestroy($image);<br>
"
;

echo "

With these steps, we can generate a dynamic CAPTCHA with noise lines and randomly rotated characters, improving form security.

"
;
?>