开发者

Applying text to png transparency issue PHP

I am trying to write text onto a png, however when I do it puts a dark border around it, I am not sure why.

The original image:

Applying text to png transparency issue PHP

The processed image:

Applying text to png transparency issue PHP

Code:

// Load the image
$im = imagecreatefrompng("admin/public/images/map/order/wally.png");

// If there's an error, gtfo
if(!$im) {
    die("");
}
$textColor = imagecolorallocate($im, 68, 68, 68);

$width = imagesx($im);
$height = imagesy($im);

$fontSize = 5; 
$text = "AC";
// Calculate the left position of the text
$leftTextPos = ($width - imagefontwidth($fontSize)*strlen($text)) / 2;
// Write the string
imagestring($im, $fontSize, $leftTextPos, $height-28, $text, $textColor);
// Out开发者_C百科put the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);


I've had this issue several times, let me find the answer...

Ok, found something:

imagesavealpha($im, true);
imagealphablending($im, true);

Write that before imagepng.


Yes, saving with alpha is important but loading it is important as well. Your PNG image might have transparency but it is good practice to account for that as well.

You'd need to create true color image, set alpha color and then draw your loaded image with text over it. So something like this:

// create true color image
$img = imagecreatetruecolor($width, $height);
$transparent_color = imagecolorallocatealpha($img, 255, 255, 255, 0);

imagealphablending($img, false);
imagefillrectangle($img, 0, 0, $width, $height, $transparent_color);
imagealphablending($img, true);

// draw previously loaded PNG image
imagecopy($img, $loaded_img, 0, 0, 0, 0, $width, $height);

// draw your text

// save the whole thing
imagesavealpha($img, true);
imagepng($img, $file);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜