具有透明/Alpha 背景的 PHP GD 文本

标签 php gd transparent imagettftext

好吧,我在将我的文本放置在部分透明的图像上时遇到了问题。我希望文本是实心的,但我希望图像的部分背景是透明的,而文本结束的部分是实心的,我有,问题是文本继承了其中一个的透明背景前几层。这是代码和输出示例,在该输出下我希望它看起来像什么。图像位于浅灰色背景上,因此深灰色之间图像周围的浅色边框是透明的,但除此之外别无其他,尤其是文本。透明的似乎不是文本本身,而是文本 block 的背景。如您所见,这不是很理想。请帮助,这是我完成项目的唯一问题。 :)

还不能发布图片,所以这里是示例输出图片和预期结果的链接 (orig):

enter image description here

<?php

$img = imagecreatetruecolor(200, 50);

$imageX = imagesx($img);
$imageY = imagesy($img);

imagealphablending($img, false);
imagesavealpha($img, true);

$transparent = imagecolorallocatealpha($img, 255,255,255, 127);
$white = imagecolorallocate($img, 255,255,255);
$grey = imagecolorallocate($img, 127,127,127);
imagefilledrectangle($img, 0, 0, $imageX, $imageY, $grey);
imagefilledrectangle($img, 2, 2, $imageX-4, $imageY-4, $transparent);

$font = "./arialbd.ttf";
$fontSize = 12;
$text = "THIS IS A TEST";

$textDim = imagettfbbox($fontSize, 0, $font, $text);
$textX = $textDim[2] - $textDim[0];
$textY = $textDim[7] - $textDim[1];

$text_posX = ($imageX / 2) - ($textX / 2);
$text_posY = ($imageY / 2) - ($textY / 2);

imagefilledrectangle($img, 10, 10, $imageX-10, $imageY-10, $grey);
imagettftext($img, $fontSize, 0, $text_posX, $text_posY, $white, $font, $text);

header("Content-Type: image/png");
imagepng($img);

?>

最佳答案

哈,我想我没有认真考虑。解决方案是在将文本放置到图像上之前重新打开 imagealphablending。

<?php

$img = imagecreatetruecolor(200, 50);

$imageX = imagesx($img);
$imageY = imagesy($img);

imagealphablending($img, false);
imagesavealpha($img, true);

$transparent = imagecolorallocatealpha($img, 255,255,255, 127);
$white = imagecolorallocate($img, 255,255,255);
$grey = imagecolorallocate($img, 127,127,127);
imagefilledrectangle($img, 0, 0, $imageX, $imageY, $grey);
imagefilledrectangle($img, 2, 2, $imageX-4, $imageY-4, $transparent);

$font = "./arialbd.ttf";
$fontSize = 12;
$text = "THIS IS A TEST";

$textDim = imagettfbbox($fontSize, 0, $font, $text);
$textX = $textDim[2] - $textDim[0];
$textY = $textDim[7] - $textDim[1];

$text_posX = ($imageX / 2) - ($textX / 2);
$text_posY = ($imageY / 2) - ($textY / 2);

imagefilledrectangle($img, 10, 10, $imageX-10, $imageY-10, $grey);
imagealphablending($img, true);
imagettftext($img, $fontSize, 0, $text_posX, $text_posY, $white, $font, $text);

header("Content-Type: image/png");
imagepng($img);

?>

关于具有透明/Alpha 背景的 PHP GD 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2134467/

相关文章:

Java (swing) gif 不应该是部分透明的

css - 在网格中覆盖透明框 css

php - 通过PHP脚本在Android中根据Checkbox点击填充MySQL表

php - 为什么会出现错误 "expected to be a reference, value given"?

PHP - 使用 GD 旋转图像会产生黑色边框

android - 使自定义 Android SurfaceView 透明

javascript - 获取级联单选按钮值的值

javascript - 为什么 Ajax 调用没有执行?

PHP-GD imagejpeg无法打开

php - 在贝塞尔曲线中添加颜色的算法