18
votes

I'm pretty sure I need to use imagefilledrectangle in order to get a white background instead of black on this... just not sure how. I've tried a few ways.

$targetImage = imagecreatetruecolor($thumbw,$thumbh);
imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,$thumbHeight,imagesx($sourceImage),imagesy($sourceImage));
3
To anyone as clueless as me. imagefill was the answer: $targetImage = imagecreatetruecolor($thumbw,$thumbh); $white = imagecolorallocate($targetImage, 255, 255, 255); imagefill($targetImage, 0, 0, $white); imagecopyresized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,$thumbHeight,imagesx($sourceImage),imagesy($sourceImage)); - Jean-Pierre Bazinet

3 Answers

41
votes

UPDATE (2020): Please see this answer below for a faster fill than imagefill: https://stackoverflow.com/a/32580839/1005039

ORIGINAL

From the PHP manual entry for imagefill:

$image = imagecreatetruecolor(100, 100);

// set background to white
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
12
votes

imagefill() uses flood fill, which is quite slow compared to just painting a color in a rectangle without regard for the content of the image. So imagefilledrectangle() will be a lot quicker.

// get size of target image
$width  = imagesx($targetImage);
$height = imagesy($targetImage);

// get the color white
$white  = imagecolorallocate($targetImage,255,255,255);

// fill entire image (quickly)
imagefilledrectangle($targetImage,0,0,$width-1,$height-1,$white);

Speed is often a consideration when writing code.

3
votes
$targetImage = imagecreatetruecolor($thumbw,$thumbh);

// get the color white
$color = imagecolorallocate($targetImage, 255, 255, 255);

// fill entire image
imagefill($targetImage, 0, 0, $color);

imagecolorallocate: http://www.php.net/manual/en/function.imagecolorallocate.php

imagefill: http://php.net/manual/en/function.imagefill.php