Problem creating a transparent background image

1

Hello,

I'm trying to create an image in PHP just like the email of offers automatically submitted by CasasBahia.

Example HomesBahia;

I searched the internet and found the following code that helped me a lot;

<?php
header('Content-type: image/png');
$text = 'R$ 10,90';
$font = 'arial.ttf';
$image  = imagecreatetruecolor(187, 44);
$color = imagecolorallocate($image, 0, 70, 140);
$background = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagettftext($image, 25, 0, 0, 33, $color, $font, $text);
imagefill($image, 0, 0, $background);
imagecolortransparent($image, $background);
imagepng($image);
imagedestroy($image);

However, when I put the script link in place of an image that would be the actual price of the product, the image was blacked out around the text.

Script preview;

I searched the internet and in forums but found nothing.

I'm using XAMPP in version 5.6.35

I use Google Chrone in version 65.0.3325.181 (last)

    
asked by anonymous 16.04.2018 / 16:38

1 answer

1

Just apply:

imagesavealpha($image, true); //canal alpha
imagealphablending($image, false); //Desabilita a mesclagem
  • imagesavealpha : Sets the option to save the entire alpha channel information (instead of the transparency of a single color) when saving PNG images.

  • imagealphablending enables or disables merge mode

It should look like this:

<?php
header('Content-type: image/png');
$text = 'R$ 10,90';
$font = 'arial.ttf';

$image  = imagecreatetruecolor(187, 44);

imagesavealpha($image, true); //canal alpha
imagealphablending($image, false); //Desabilita a mesclagem

$color = imagecolorallocate($image, 0, 70, 140);
$background = imagecolorallocatealpha($image, 0, 0, 0, 127);

imagefill($image, 0, 0, $background);
imagecolortransparent($image, $background);

imagettftext($image, 25, 0, 0, 33, $color, $font, $text);

imagepng($image);
imagedestroy($image);

See the result:

    
17.04.2018 / 06:20