使用PHP生成图片时,背景色始终错误。

7

当用户上传一张图片时,程序将生成一个新的白色背景的正方形图像,并将用户的图片放置在该图像的中心。

但问题是,我将背景设置为白色,它总是显示黑色。

代码如下:

$capture = imagecreatetruecolor($width, $height);
$rgb = explode(",", $this->background); 
$white = imagecolorallocate($capture, $rgb[0], $rgb[1], $rgb[2]); 
imagefill($capture, 0, 0, $white); 

控制颜色的代码是: protected $background = "255,255,255";

我试图将$white = imagecolorallocate($capture, $rgb[0], $rgb[1], $rgb[2]);更改为$white = imagecolorallocate($capture, 255, 255, 255);,但背景仍然显示为黑色。

感谢任何答案。


“not working”是什么意思?背景颜色是什么?另外,你是如何渲染图像的? - Zach Rattner
@Zach Rattner,它仍然显示为黑色而不是白色。我使用imagejpeg来渲染图像。 - Juni
1
$im = @imagecreatetruecolor(120, 20) or die('无法初始化新的GD图像流'); $rgb = explode(",", "255,255,255"); $white = imagecolorallocate($im, $rgb[0], $rgb[1], $rgb[2]); imagefill($im, 0, 0, $white); imagejpeg($im);``` 对我来说是有效的,您确定您没有在后面覆盖它吗? - Deebster
@Deebster 谢谢。我发现我没有改变 $rgb = explode。但仍需要使用 imagefilledrectangle() 函数。 - Juni
2个回答

6
从手册中可以得知,imagecreatetruecolor()返回一个图像标识符,它代表指定尺寸的黑色图像。对于基于调色板的图像,第一次调用imagecolorallocate函数可以设置背景色,但是对于真彩色图像则不行。
在真彩色图像上设置背景色的方法是用一个实心矩形来填充它。
imagefilledrectangle($capture, 0, 0, $width, $height, $white);

矩形功能正常,但我还需要将 $rgb = explode(",", $this->background); 更改为 $rgb = explode(",", "255,255,255"); - Juni

1

那么 imagefill($im, x, y, $color) 呢?

$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $red);

这将用红色填充整个图像,x,y参数是矩形填充的起始点。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接