Current Location: Home> Latest Articles> How to use the imagecolorallocatealpha function combined with imagettftext() to add transparent text effect?

How to use the imagecolorallocatealpha function combined with imagettftext() to add transparent text effect?

M66 2025-05-17

When using PHP for image processing, the GD library provides a wealth of functions to achieve various effects. where imagettftext() can be used to draw text in TrueType font on the image, while imagecolorallocatealpha() can be assigned a color with transparency. When we use these two functions in combination, we can add text with transparent effects to the image.

This article will use an example to demonstrate how to achieve this effect.

Step 1: Create a canvas

First, we need to create a canvas. Here we use imagecreatetruecolor() to create a true color image:

 <?php
// Create a picture 400x200 Canvas
$width = 400;
$height = 200;
$image = imagecreatetruecolor($width, $height);

// Assign white to the background
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);

Step 2: Assign text colors with transparency

The fourth parameter of imagecolorallocatealpha() represents transparency, with values ​​ranging from 0 (completely opaque) to 127 (completely transparent).

 // Assign red,50% transparency(Approximately equal to alpha = 63)
$red_alpha = imagecolorallocatealpha($image, 255, 0, 0, 63);

Step 3: Draw the text

We use imagettftext() to draw text on the canvas. You need to provide a path to the TTF font file.

 // Font file path
$font_path = __DIR__ . '/arial.ttf';

// Write text on canvas
imagettftext(
    $image,        // Image Resources
    30,           // Font size
    0,            // angle
    50,           // X coordinate
    100,          // Y coordinate(Baseline location)
    $red_alpha,   // color(带transparency)
    $font_path,   // Font file path
    'Hello, m66.net!' // Text to be written
);

Step 4: Output the picture

In order to output PNG images with transparency, you need to set the transparent color and output it to PNG format.

 // Open alpha Channel Mixing
imagesavealpha($image, true);

// Set the output header
header('Content-Type: image/png');

// Output picture
imagepng($image);

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

Tips

  • Make sure the GD library is installed on the server and that support for TrueType fonts is enabled in php.ini .

  • The closer the transparency value of imagecolorallocatealpha() is to 127, the more transparent the effect is.

  • When using imagepng() output, transparent channels can be better preserved.