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.
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);
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);
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
);
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);
?>
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.