Current Location: Home> Latest Articles> imagettftext Use with imageline to implement complex graphics

imagettftext Use with imageline to implement complex graphics

gitbox 2025-05-29

2. Combined use scenario analysis

Using imagettftext() and imageline() in combination can be applied to the following scenarios:

  1. Generate an annotated line chart

  2. Dynamic flow chart

  3. Combining slash interference in verification code with dynamic font

  4. Text logos in graphic buttons or structural diagrams

Through appropriate coordinate calculations, we can accurately align text with graphics and enhance visual effects.


3. Example: Create an annotated line segment diagram

The following example shows how to create an image with a line segment and text descriptions added to the starting and end points of the line segment.

 <?php
// Create a canvas
$width = 400;
$height = 300;
$image = imagecreatetruecolor($width, $height);

// Color distribution
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);

// Fill the background
imagefill($image, 0, 0, $white);

// Define fonts
$font = __DIR__ . '/arial.ttf'; // make surearial.ttfFont file exists

// Draw lines
$x1 = 50; $y1 = 250;
$x2 = 350; $y2 = 50;
imageline($image, $x1, $y1, $x2, $y2, $blue);

// Add text(Line starting point)
imagettftext($image, 12, 0, $x1 - 30, $y1 + 20, $black, $font, 'starting point');

// Add text(Line end point)
imagettftext($image, 12, 0, $x2 + 10, $y2, $black, $font, 'end');

// Output image
header('Content-Type: image/png');
imagepng($image);

// Destroy resources
imagedestroy($image);
?>

The code creates an image with a white background, draws a blue line segment on the image, and adds comment text at the beginning and end points respectively. imagettftext() enables text to be placed and rotated arbitrarily, and imageline() is used to draw graphic elements. The combination of the two can form a diverse infographic.


4. Advanced application: Generate graphic descriptions based on URL information

More complex uses can be achieved by drawing tag text in the graph, such as hyperlink titles, such as graphical site maps, process tips, etc.:

 $url = 'https://gitbox.net/api/step?id=42';
$text = 'check the details';

// Extract information and draw
imagettftext($image, 10, 0, 150, 100, $black, $font, $text);

Although the image cannot be directly clicked and redirected, the generated image can be used as a visual prompt for web anchors in conjunction with HTML to improve user experience.