20

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));
1
  • 2
    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)); Nov 15, 2011 at 18:09

3 Answers 3

44

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);
1
  • Hi @user3473227 - Your edit was actually correct. I've updated my answer to reflect your change. (Sorry it got rejected.) Feb 19, 2015 at 12:45
15

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.

2
  • with imagefill a I have a problem "memory exausted", imagefilledrectangle solve. tks Aug 24, 2017 at 18:26
  • 1
    This should be accepted as correct answer. "imagefill()" is really slow compared to this solution and it can cause issues on servers with low memory limit.
    – Tom F.
    Jun 1, 2020 at 10:38
3
$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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.