stil / gd-text

PHP class making it easy to type text on pictures. Supports multi-lined text, horizontal and vertical alignment.
400 stars 131 forks source link

strokeText is too slow! #57

Open alikm6 opened 3 years ago

alikm6 commented 3 years ago

strokeText is very slow for high input (eg 10).

The following code is much more efficient (up to 40 times faster for strokeText = 10)

protected function strokeText($x, $y, $text)
    {
        $size = $this->strokeSize;
        if ($size <= 0) return;

        /*
        // Current algorithm
        for ($c1 = $x - $size; $c1 <= $x + $size; $c1++) {
            for ($c2 = $y - $size; $c2 <= $y + $size; $c2++) {
                $this->drawInternal(new Point($c1, $c2), $this->strokeColor, $text);
            }
        }
        */

        $tmp_box = $this->calculateBox($text);

        $textWidth = $tmp_box->getWidth();
        $textHeight = 1.5 * $tmp_box->getHeight();

        $tmp_img = imagecreatetruecolor($textWidth, $textHeight);
        imagesavealpha($tmp_img, true);
        imagefill($tmp_img, 0, 0, imagecolorallocatealpha($tmp_img, 0, 0, 0, 127));

        imagettftext(
            $tmp_img,
            $this->getFontSizeInPoints(),
            0, // no rotation
            0,
            $tmp_box->getHeight(),
            $this->strokeColor->getIndex($tmp_img),
            $this->fontFace,
            $text
        );

        for ($c1 = $x - $size; $c1 <= $x + $size; $c1++) {
            for ($c2 = $y - $size; $c2 <= $y + $size; $c2++) {
                imagecopy($this->im, $tmp_img, $c1, $c2 - $tmp_box->getHeight(), 0, 0, $textWidth, $textHeight);
            }
        }

        imagedestroy($tmp_img);
    }