PHP imagick COMPOSITE_DSTIN结果为黑色背景

时间:2019-06-20 00:12:01

标签: php imagick

我尝试在https://www.sitepoint.com/community/t/gd-text-gradient/82127/9

处通过此解决方案设置文本渐变

但是最终图像的背景颜色是黑色,我尝试使用$im->flattenImages$img->setBackgroundColor,但是它不起作用。

$im = new Imagick();

        $draw = new ImagickDraw();
        $draw->setFontSize(90);
        $draw->setFillColor(new ImagickPixel("black"));
        $draw->setTextEncoding('UTF-8');
        $draw->setGravity(Imagick::GRAVITY_CENTER);

        $metric = $im->queryFontMetrics($draw, $text);

        $width = $metric['textWidth'];
        $height = $metric['textHeight'];

        /* Create and save the gradiant */
        $Imagick = new Imagick();
        $Imagick->newPseudoImage($height, $width, "gradient:#FB7F4C-#FF409C");
        /*** rotate the image ***/
        $Imagick->rotateImage(new ImagickPixel(), 270);
        $Imagick->setImageFormat('png');
        $Imagick->writeImage("gradiant.png");

        /* Create and save the canvas */
        $im->newPseudoImage($width, $height, "null:");
        $im->setImageFormat('png');
        $im->writeImage("canvas.png");

        /* Add the text to the canvas ( Make the mask )*/
        $im = new Imagick("canvas.png");

// Write the text on the image
        $im->annotateImage($draw, 0, 0, 0, $text);
        $im->setImageBackgroundColor("transparent"); // <= Here
        /* Final image */
        $canvas = new Imagick("gradiant.png");
        $canvas->compositeImage($im, imagick::COMPOSITE_DSTIN, 0, 0, Imagick::CHANNEL_ALPHA);

        $canvas->setImageFormat('png');
        $canvas->writeImage(__DIR__ . "/../../final.png");

        header('Content-Type: image/' . $im->getImageFormat());
        echo $canvas;

        unlink("canvas.png");
        unlink("gradiant.png");

我在COMPOSITE_DSTIN之后发现背景颜色变黑,我尝试了很多方法但不起作用

如何删除黑色背景?

1 个答案:

答案 0 :(得分:3)

我通过添加alphachannel解决了该问题

我尝试$canvas->setImageAlphaChannel(Imagick::ALPHACHANNEL_RESET);,然后背景保持透明