Problem when creating an image with transparent background

Asked

Viewed 665 times

1

Hello,

I’m trying to create a PHP image like the emails of offers sent automatically by Casasbahia.

Example of the Casasbahia;

Exemplo das CasasBahia

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 real price of the product, the image was with black pixels around the text.

Preview of the script;

Pré-visualização do script

I searched the internet and forums but found nothing.

I am using XAMPP in version 5.6.35

I use Google Chrone in version 65.0.3325.181 (latest)

  • Post an image of how the rendering is on the screen. And which browser you are testing?

  • Added @hugocsl

1 answer

1


Just apply:

imagesavealpha($image, true); //canal alpha
imagealphablending($image, false); //Desabilita a mesclagem
  • imagesavealpha: Set the option to save the full alpha Channel information (instead of the one-color transparency) when saving PNG images.

  • imagealphablending enables or disables merge mode

Should stay 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:

resultado com imagesavealpha e imagealphablending

  • Thanks! It worked perfectly. imagettftext the imagefill and imagecolortransparent and ready!

  • @Gustavodias strange, here worked normal, can be a bug of your version of PHP or something, anyway I approved your edition for the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.