View Full Version : GD imagecopy problems with black background

08-15-2006, 05:58 PM
This function is part of a class, it basically creates a new image in the dimensions specified, and then copies in the image held in $this->image. The image that is copied in will never be bigger than the new image (that is taken care of in another function) but one or both of the dimensions could be less than the new image (if the ratio isnít the same).

It all works perfectly, it creates a new true colour image, fills it in white, but then when it runs the imagecopy function it seems to forget the fact that I set the background to white, and the image that results has a black border.

For example if I wanted a 100x100 image, and I was copying a 100x50 image in, I would end up with a 100x100 image with the old image centred vertically and a 25px black stripe above and below, I want those stripes to be white.

Any ideas?

function crop($width = null, $height = null)
// get the current widths and heights
$current_width = imagesx($this->image);
$current_height = imagesy($this->image);

$crop_top = floor(($current_width - $width) / 2);
$crop_left = floor(($current_height - $height) / 2);

// create a new image resource
$temp = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($temp, 255, 255, 255);
imagefill($temp, 0, 0, $white);

// copy image into new resource
imagecopy($temp, $this->image, 0, 0, $crop_top, $crop_left, $width, $height);

// destroy original image

// copy new image
$this->image = $temp;

Thanks in advance,

P.S. This function probably shouldnt actually be called crop, as thats not what it does, incase that confused anyone.

08-15-2006, 08:04 PM
Is the image you are copying into $temp a true color image? If it is paletted (gif for example), you'll probably need to do imagecreate() instead of imagecreatetruecolor(). (That's my guess)

08-16-2006, 11:28 AM
Yeah it is a true colour image, a JPEG.

01-25-2007, 11:06 PM
on a related note I'm having problems with gd thumbnail rendering and can't seem to find a solution anywhere.
have you heard of this issue or are you having any luck finding out why gd is generating a black background?
the issues may be related . . .