Juni Juni - 9 months ago 28
PHP Question

use php to generate image, the background is always in wrong color

The function is when users upload a picture, program will generate a new white background squre image, and put user's picture in the center of this image.

But the problem is, I set the background to white, it always shows black.

The code is

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

and the code that controls the color is
protected $background = "255,255,255";

I've been tried to change
$white = imagecolorallocate($capture, $rgb[0], $rgb[1], $rgb[2]);
$white = imagecolorallocate($capture, 255, 255, 255);
. But the background still shows in black.

Thanks for any answer


From the manual imagecreatetruecolor() returns an image identifier representing a black image of the specified size. The first call to imagecolorallocate sets the background for palette based images but a true color image is not.

The way I set the background color on true color images is to just fill it with a solid rectangle.

imagefilledrectangle($capture, 0, 0, $width, $height, $white);