Php imagettftext creates black edges on transparent background

I have this code:

$im = imagecreatetruecolor(70, 25); $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0); imagecolortransparent($im, imagecolorallocate($im, 0,0,0)); $font = 'font.ttf'; imagettftext($im, 20, 0, 3, 22, $white, $font, $randomnr); header("Expires: Wed, 1 Jan 1997 00:00:00 GMT"); header("Last-Modified: " . gmdate("D, d MYH:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header ("Content-type: image/png"); imagepng($im); imagedestroy($im); 

And, as I said in the title, it creates some black edges around the text. I also tried using imagealphablending / imagesavealpha and I had the same result (I used white text on a transparent background so you can see what I'm talking about):

black edges

UPDATE: solution:

 $im = imagecreatetruecolor(70, 25); $font = 'font.ttf'; //antialiasing: $almostblack = imagecolorallocate($im,254,254,254); imagefill($im,0,0,$almostblack); $black = imagecolorallocate($im,0,0,0); imagecolortransparent($im,$almostblack); imagettftext($im, 20, 0, 3, 22, $white, $font, $randomnr); ... 
+4
source share
2 answers

Here is what you indicated here:

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

If you want to use some other color for transparent, choose a different color. You are using black color right now.

See imagecolortransparent Documents .

Also note this user note on the same page:

Transparent background with text does not work very well due to anti-aliasing.

+2
source

Something like this should do the job:

 $width = 70; $height = 25; $im = imagecreatetruecolor($width, $height); $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 221, 221, 221); imageSaveAlpha($im, true); imageAlphaBlending($im, false); $transparent = imageColorAllocateAlpha($im, 0, 0, 0, 127); imagefilledrectangle($im, 0, 0, $width-1, $height-1, $transparent); imageAlphaBlending($im, true); $font = 'font.ttf'; $randomnr = "1234"; imagettftext($im, 20, 0, 3, 22, $white, $font, $randomnr); header("Expires: Wed, 1 Jan 1997 00:00:00 GMT"); header("Last-Modified: " . gmdate("D, d MYH:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header ("Content-type: image/png"); imagepng($im); imagedestroy($im); 
+6
source

Source: https://habr.com/ru/post/1437176/


All Articles