php-watermark icon indicating copy to clipboard operation
php-watermark copied to clipboard

Text color

Open shqawe1 opened this issue 2 years ago • 1 comments

Hi,

Is there any plan to update this package to have text color functionality?

Actually i tried to change rgba color in this function getDuelTextColor but unfortunately it does't work.

Can you give me a hand in this if you don't plan to update this package soon.

shqawe1 avatar Aug 12 '23 08:08 shqawe1

After searching and testing i think i got it to work with rgb and rgba format.

First we should modify options array in Watermark Class in Watermark.php file and we add this option as below:

'fontcolor' => '#ffffff',

Then create new function in same Watermark class as below:

`

    public function setFontColor($fontColor)
        {
            $this->options['fontcolor'] = $this->_colorToRGB($fontColor);
        }

    private function _colorToRGB($hex)
    {
    $hex = strtolower($hex);

    if (strpos($hex, 'rgba') !== false) {
        preg_match('/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/i', $hex, $rgb);

        if ($rgb) {
            if (!empty($rgb[4])) {
                $this->setOpacity(intval(127 - 127 * $rgb[4]));
            }

            return [$rgb[1], $rgb[2], $rgb[3]];
        }
    }

    if (strpos($hex, 'rgb') !== false) {
        preg_match('/^rgb\(\s*(\d+%?)\s*,\s*(\d+%?)\s*,\s*(\d+%?)\s*\)$/i', $hex, $rgb);

        if ($rgb) {
            return [$rgb[1], $rgb[2], $rgb[3]];
        }
    } else {
        $hex = str_replace('#', '', $hex);

        if (utf8_strlen($hex) == 3) {
            $r = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
            $g = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
            $b = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
        } else {
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
        }

        return [$r, $g, $b];
            }

            return [0, 0, 0];
        }`

Save the file and open ImageCommandBuilder.php file and modify getDuelTextColor function to be like below:

protected function getDuelTextColor() { return [ 'fill "' . $this->options['fontcolor'] . '\ "', "fill \"rgba\\(0,0,0,0.4\\)\"", ]; }

And finally we can use it like this

$watermark->setFontColor('rgba(255,255,255,0)');

I hope it help and thanks for this package it's was really helpful for my project and jzak allah kher.

shqawe1 avatar Aug 14 '23 14:08 shqawe1