简体   繁体   English

将文本应用于png透明度问题PHP

[英]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. 我正在尝试将文本写入png,但是当我这样做时会在它周围放置一个黑色边框,我不知道为什么。

The original image: 原始图片:

The processed image: 处理后的图片:

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);
// Output 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 . imagepng之前imagepng

Yes, saving with alpha is important but loading it is important as well. 是的,使用alpha保存很重要,但加载它也很重要。 Your PNG image might have transparency but it is good practice to account for that as well. 您的PNG图像可能具有透明度,但最好也考虑到这一点。

You'd need to create true color image, set alpha color and then draw your loaded image with text over it. 您需要创建真彩色图像,设置Alpha颜色,然后在其上绘制带有文本的加载图像。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM