为了改进“php at lfbittencourt dot com”的解决方案,这个方案混合了合成颜色,并考虑了不透明度。
<?php
class YourImagick extends Imagick
{
public function colorize($color, $alpha = 1, $composite_flag = Imagick::COMPOSITE_COLORIZE)
{
$draw = new ImagickDraw();
$draw->setFillColor($color);
$geometry = $this->getImageGeometry();
$width = $geometry['width'];
$height = $geometry['height'];
$draw->rectangle(0, 0, $width, $height);
$temporary = new Imagick();
$temporary->setBackgroundColor(new ImagickPixel('transparent'));
$temporary->newImage($width, $height, new ImagickPixel('transparent'));
$temporary->setImageFormat('png32');
$temporary->drawImage($draw);
$alphaChannel = $this->clone();
$alphaChannel->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
$alphaChannel->negateImage(false, Imagick::CHANNEL_ALL);
$this->setImageClipMask($alphaChannel);
$clone = $this->clone();
$clone->compositeImage($temporary, $composite_flag, 0, 0);
$clone->setImageOpacity($alpha);
$this->compositeImage($clone, Imagick::COMPOSITE_DEFAULT, 0, 0);
}
}
?>