ImagickDriver.php 12.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
<?php
/**
 * Author: lang
 * Email: 732853989@qq.com
 * Date: 2023/3/24
 * Time: 11:31
 */

namespace Kkokk\Poster\Image\Drivers;

use Kkokk\Poster\Common\Common;
use Kkokk\Poster\Exception\PosterException;
use Kkokk\Poster\Image\Traits\ImagickTrait;

class ImagickDriver extends Driver implements DriverInterface
{
    use ImagickTrait;

    protected $ImagickDraw;

    function __construct()
    {

    }

    public function getData($path = '')
    {
        if ($path) {
            $this->setFilePath($path);
        }
        $this->setDPI();
        return $this->returnImage($this->type);
    }

    public function getStream()
    {
        $this->setDPI();
        return $this->returnImage($this->type, false);
    }

    public function getBaseData()
    {
        $this->setDPI();
        $common = new Common();
        return $common->baseData($this->im->getImageBlob(), $this->type);
    }

    public function setData()
    {
        $this->setDPI();
        return $this->setImage($this->source);
    }

    public function im($w, $h, $rgba = [255, 255, 255, 1], $alpha = false)
    {
        $this->im_w = $w;
        $this->im_h = $h;
        $this->im = $this->createIm($w, $h, $rgba, $alpha);
    }

    public function ImDst($source, $w = 0, $h = 0)
    {
        // if (!is_file($source)) {
        //     throw new PosterException('水印图像不存在');
        // }
        $this->source = $source;

        $pic = $this->createImagick($source);

        $bgWidth = $pic->getImageWidth();
        $bgHeight = $pic->getImageHeight();
        $this->type = strtolower($pic->getImageFormat());

        if (!empty($w) && !empty($h)) {
            $this->im_w = $w;
            $this->im_h = $h;
            $pic->resizeImage($w, $h, $pic::FILTER_LANCZOS, 1, true);
        } else {
            $this->im_w = $bgWidth;
            $this->im_h = $bgHeight;
        }

        $this->im = $pic;
    }

    public function Bg($w, $h, $rgba = [], $alpha = false, $dst_x = 0, $dst_y = 0, $src_x = 0, $src_y = 0, $query = [])
    {
        // 判断颜色是否渐变
        $rgbaColor = isset($rgba['color']) ? $rgba['color'] : [[0, 0, 0]];
        $alphas = isset($rgba['alpha']) ? $rgba['alpha'] : 1;
        $to = isset($rgba['to']) ? $rgba['to'] : 'bottom';
        $radius = isset($rgba['radius']) ? $rgba['radius'] : 0;
        $contentAlpha = isset($rgba['content_alpha']) ? $rgba['content_alpha'] : false;
        $rgbaCount = count($rgbaColor);

        // im不存在则创建
        if (empty($this->im)) {
            $this->im($w, $h, [], $alpha);
        }
        // 渐变处理->直接处理im
        // 计算颜色方向
        $pic = $this->createIm($w, $h, [], $alpha);
        $this->calcColorDirection($pic, $rgbaColor, $rgbaCount, $to, $w, $h);

        // 设置透明度,内容不透明
        if($alpha && !$contentAlpha) {
            $pic->setImageAlpha(floor((128 - $alphas) / 127 * 100) / 100); // 透明度
        }

        $dst_x = $this->calcDstX($dst_x, $this->im_w, $w);
        $dst_y = $this->calcDstY($dst_y, $this->im_h, $h);

        if (!empty($query)) {
            $that = clone $this;
            $that->im = $pic;
            $that->im_w = $w;
            $that->im_h = $h;
            $that->execute($query, $that);

            // 合并图片, 合并图片移到下方,这里不需要再合并
            // $pic->compositeImage($that->im, ($that->im)::COMPOSITE_DEFAULT, $dst_x, $dst_y);
        }

        // 设置透明度,内容也透明
        if($alpha && $contentAlpha) {
            $pic->setImageAlpha(floor((128 - $alphas) / 127 * 100) / 100); // 透明度
        }

        if ($radius) {
            // 圆角处理
            $pic = $this->setPixelRadius($pic, $w, $h, $radius);
        }

        // 裁剪图片
        $this->cropImage($pic, $src_x, $src_y);

        // 合并图片
        $this->im->compositeImage($pic, ($this->im)::COMPOSITE_DEFAULT, $dst_x, $dst_y);

        if($that) unset($that);
        $this->destroyImage($pic);
    }

    public function CopyImage($src, $dst_x = 0, $dst_y = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0, $alpha = false, $type = 'normal')
    {
        if (empty($this->im)) throw new PosterException('im resources not be found');

        if (strpos($src, 'http') === false) {
            $src = $this->getRealRoute($src);
        }

        $pic = $this->createImagick($src);

        $Width = $pic->getImageWidth();
        $Height = $pic->getImageHeight();

        $bgWidth = !empty($src_w) ? $src_w : $Width;
        $bgHeight = !empty($src_h) ? $src_h : $Height;

        switch ($type) {
            case 'normal':
                # 自定义宽高的时候
                if (!empty($src_w) && !empty($src_h)) {
                    $pic->resizeImage($bgWidth, $bgHeight, $pic::FILTER_LANCZOS, 1, true);
                }
                break;
            case 'circle':
                if (!empty($src_w) && !empty($src_h)) {
                    $pic->resizeImage($bgWidth, $bgHeight, $pic::FILTER_LANCZOS, 1, true);
                }
                // 创建一个圆形遮罩图片

                $mask = $this->createImagick();

                $mask->newImage($bgWidth, $bgHeight, $this->createColorAlpha([255, 255, 255, 127]));

                $circle = $this->createImagickDraw();
                $circle->setFillColor($this->createColorAlpha([255, 255, 255, 1]));
                $circle->circle($bgWidth / 2, $bgHeight / 2, $bgWidth / 2, $bgHeight);

                $mask->drawImage($circle);

                // 合并原始图片和圆形遮罩图片
                $pic->compositeImage($mask, $pic::COMPOSITE_DSTIN, 0, 0);

                $this->destroyImage($circle);
                $this->destroyImage($mask);
                break;
            default:
                # code...
                break;
        }

        # 处理目标 x 轴
        $dst_x = $this->calcDstX($dst_x, $this->im_w, $bgWidth);

        # 处理目标 y 轴
        $dst_y = $this->calcDstY($dst_y, $this->im_h, $bgHeight);

        // 裁剪图片
        $this->cropImage($pic, $src_x, $src_y);
        // 合并图片
        $this->im->compositeImage($pic, ($this->im)::COMPOSITE_DEFAULT, $dst_x, $dst_y);


        $this->destroyImage($pic);
    }

    public function CopyText($content, $dst_x = 0, $dst_y = 0, $fontSize = null, $rgba = null, $max_w = null, $font = null, $weight = null, $space = null, $angle = null)
    {
        if ($content == '') return true;

        if (empty($this->im)) throw new PosterException('im resources not be found');

        $fontSize = $fontSize ?: $this->font_size;
        $rgba = $rgba ?: $this->font_rgba;
        $max_w = $max_w ?: $this->font_max_w;
        $weight = $weight ?: $this->font_weight;
        $space = $space ?: $this->font_space;
        $angle = $angle ?: $this->font_angle;

        if (!empty($font)) {
            $font = $this->getRealRoute($font);
        } else {
            $font = $this->font;
        }

        $calcSpace = $space > $fontSize ? ($space - $fontSize) : 0; // 获取间距计算值

        $color = $this->createColorAlpha($rgba);

        // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $contents = '';
        $letter = [];

        // 将字符串拆分成一个个单字 保存到数组 letter 中
        for ($i = 0; $i < mb_strlen($content); $i++) {
            $letter[] = mb_substr($content, $i, 1);
        }

        $max_ws = $this->im_w;
        if (isset($max_w) && !empty($max_w)) {
            $max_ws = $max_w;
        }

        $draw = $this->createTextImagickDraw();
        $draw->setFont($font);
        $draw->setFillColor($color);
        $draw->setFontSize($fontSize);

        $line = 1;
        $calcSpaceRes = 0;
        foreach ($letter as $l) {
            $textStr = $contents . ' ' . $l;
            $fontBox = $this->im->queryFontMetrics($draw, $textStr);
            $textWidth = abs($fontBox['textWidth'] + $fontBox['descender']) + $calcSpaceRes;
            // 判断拼接后的字符串是否超过预设的宽度
            if (($textWidth > $max_ws) && ($contents !== '')) {
                $contents .= "\n";
                $line++;
            }
            $contents .= $l;
            $line === 1 && $calcSpaceRes += $calcSpace;
        }

        $calcFont = [
            'text_width' => $textWidth,
            'text_height' => abs($fontBox['textHeight'] + $fontBox['descender']),
        ];
        $dst_x = $this->calcTextDstX($dst_x, $calcFont) - $fontBox['descender']; // 调整和 gd 的误差值

        $dst_y = $this->calcTextDstY($dst_y, $calcFont);

        $fontSize = ($fontSize * 3) / 4; // 使和gd一致

        # 自定义间距
        if ($space > 0) {
            $dst_x_old = $dst_x;
            for ($j = 0; $j < mb_strlen($contents); $j++) {
                $spaceStr = mb_substr($contents, $j, 1);
                if ($spaceStr == "\n") {
                    $dst_x = $dst_x_old;
                    $dst_y += 1.75 * $fontSize;
                    continue;
                }
                $this->fontWeight($draw, $weight, $fontSize, $angle, $dst_x, $dst_y, $spaceStr);
                $dst_x += $space;
            }

        } else {
            $this->fontWeight($draw, $weight, $fontSize, $angle, $dst_x, $dst_y, $contents);
        }
    }

    public function CopyLine($x1 = 0, $y1 = 0, $x2 = 0, $y2 = 0, $rgba = [], $type = '', $weight = 1)
    {
        $color = $this->createColorAlpha($rgba);
        $draw = $this->createImagickDraw();
        $draw->setStrokeColor($color);
        $draw->setStrokeWidth($weight);
        switch ($type) {
            case 'rectangle':
                $draw->setFillColor($this->createColorAlpha());
                $draw->rectangle($x1, $y1, $x2, $y2);
                break;
            case 'filled_rectangle':
            case 'filledRectangle':
                $draw->rectangle($x1, $y1, $x2, $y2);
                break;
            default:
                $draw->line($x1, $y1, $x2, $y2);
                break;
        }
        $this->im->drawImage($draw);
    }

    public function CopyArc($cx = 0, $cy = 0, $w = 0, $h = 0, $s = 0, $e = 0, $rgba = [], $type = '', $style = '', $weight = 1)
    {
        $color = $this->createColorAlpha($rgba);
        $draw = $this->createImagickDraw();
        $draw->setStrokeColor($color);
        $draw->setStrokeWidth($weight);
        $wr = $w / 2;
        $hr = $h / 2;
        switch ($type) {
            case 'filled_arc':
            case 'filledArc':
                $draw->arc($cx - $wr, $cy - $hr, $cx + $wr, $cy + $hr, $s, $e);
                break;
            default:
                $draw->setFillColor($this->createColorAlpha());
                $draw->arc($cx - $wr, $cy - $hr, $cx + $wr, $cy + $hr, $s, $e);
                break;
        }
        $this->im->drawImage($draw);
    }

    public function CopyQr($text, $size = 4, $margin = 1, $dst_x = 0, $dst_y = 0, $src_x = 0, $src_y = 0, $src_w = 0, $src_h = 0)
    {
        if (empty($this->im)) throw new PosterException('im resources not be found');

        $qr = \QRcode::re_png($text, $size, $margin);

        $bgWidth = imagesx($qr);
        $bgHeight = imagesy($qr);

        ob_start(); // 打开一个输出缓冲区
        $this->poster_type['png']($qr); // 将 GD 图像输出到缓冲区
        $imageData = ob_get_contents(); // 从缓冲区中读取图像数据
        ob_end_clean();

        $pic = $this->createImagick();
        $pic->readImageBlob($imageData);

        if ($src_w > 0) {
            $bgWidth = $src_w;
        }

        if ($src_h > 0) {
            $bgHeight = $src_h;
        }

        # 处理目标 x 轴
        $dst_x = $this->calcDstX($dst_x, $this->im_w, $bgWidth);

        # 处理目标 y 轴
        $dst_y = $this->calcDstY($dst_y, $this->im_h, $bgHeight);

        # 自定义宽高的时候
        if (!empty($src_w) && !empty($src_h)) {
            $pic->resizeImage($bgWidth, $bgHeight, $pic::FILTER_LANCZOS, 1, true);
        }

        // 裁剪图片
        $this->cropImage($pic, $src_x, $src_y);
        // 合并图片
        $this->im->compositeImage($pic, ($this->im)::COMPOSITE_DEFAULT, $dst_x, $dst_y);

        !is_resource($qr) || imagedestroy($qr);
        $this->destroyImage($pic);
    }

    public function execute($query = [], Driver $driver = null)
    {

        if (empty($driver)) {
            $driver = $this;
        }
        foreach ($query as $item) {
            $driver->run($item, $driver);
        }

        return $driver;
    }

    public function destroyImage($Imagick)
    {
        empty($Imagick) || $Imagick->destroy();
    }

    /**
     * 析构方法,用于销毁图像资源
     */
    public function __destruct()
    {
        empty($this->im) || $this->im->destroy();
        empty($this->ImagickDraw) || $this->ImagickDraw->destroy();
    }
}