Skip to content
Advertisement

How to write text with opacity on a picture in PHP?

I’m writing a text on a picture. So far everything is fine, but I have to lower the transparency or opacity value of this text. I tried the following methods for the opacity value, but I couldn’t get any results.

imagecolortransparent($image, imagecolorallocate($image, 0,0,0));



header('Content-type: image/jpeg');
$size = 50;
$degrees = 0;
$rl = 200;
$xy = 120;
$font = 'arial.ttf';
$text = "Watermark Text";
$image = imagecreatefromjpeg('image.jpg');
$textcolor = imagecolorallocate($image, 230, 230, 230);
imagettftext($image, $size, $degrees ,$rl, $xy, $textcolor, $font, $text);
imagejpeg($image); 
imagedestroy($image);

Actual result : https://prnt.sc/vy8axf

Expected result : https://prnt.sc/vy8cnz

Advertisement

Answer

You could use imagecolorallocatealpha() to assign alpha channel to $textcolor :

$textcolor = imagecolorallocatealpha($image, 230, 230, 230, 100);

Ex:

$size = 50;
$degrees = 0;
$rl = 200;
$xy = 120;
$font = 'arial.ttf';
$text = "Watermark Text";

$image = imagecreatefromjpeg('image.jpg');
$textcolor = imagecolorallocatealpha($image, 230, 230, 230, 100);
imagettftext($image, $size, $degrees ,$rl, $xy, $textcolor, $font, $text);

header('Content-type: image/jpeg');
imagejpeg($image);
imagedestroy($image);

Note that :

A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement