Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

image

gd

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

like image 215
codefile Avatar asked Nov 17 '25 10:11

codefile


1 Answers

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.

like image 180
Syscall Avatar answered Nov 19 '25 02:11

Syscall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!