/**
* Method to apply a background color to an image resource.
*
* @param array $options An array of options for the filter.
* color Background matte color
*
* @return void
*
* @since 3.4
* @throws \InvalidArgumentException
*/
public function execute(array $options = [])
{
// Validate that the color value exists and is an integer.
if (!isset($options['color'])) {
throw new \InvalidArgumentException('No color value was given. Expected string or array.');
}
$colorCode = $options['color'] ?? null;
// Get resource dimensions
$width = imagesx($this->handle);
$height = imagesy($this->handle);
// Sanitize color
$rgba = $this->sanitizeColor($colorCode);
// Enforce alpha on source image
if (imageistruecolor($this->handle)) {
imagealphablending($this->handle, false);
imagesavealpha($this->handle, true);
}
// Create background
$bg = imagecreatetruecolor($width, $height);
imagesavealpha($bg, empty($rgba['alpha']));
// Allocate background color.
$color = imagecolorallocatealpha($bg, $rgba['red'], $rgba['green'], $rgba['blue'], $rgba['alpha']);
// Fill background
imagefill($bg, 0, 0, $color);
// Apply image over background
imagecopy($bg, $this->handle, 0, 0, 0, 0, $width, $height);
// Move flattened result onto current handle.
// If handle was palette-based, it'll stay like that.
imagecopy($this->handle, $bg, 0, 0, 0, 0, $width, $height);
// Free up memory
imagedestroy($bg);
}