<?php
namespace app\service;

use think\Exception;

/**
 * GD2库绘画
 * Class GdTool
 * @package app\service
 */
class GdTool
{

    /**
     * 生成海报
     * 背景尺寸固定: 750 * 1334
     *
     * @param string $srcQr 生成的二维码base64值
     * @param string $bgImg 背景图片 自定义背景图
     * @param string $savePath 海报保存路径,为空则返回base64值
     * @return bool|string
     * @throws \Exception
     */
    public static function generatePoster(string $srcQr='', string $bgImg = '', string $savePath = '')
    {
        try {
            if (!empty($savePath)) {
                if (!is_dir($savePath)) {
                    @mkdir($savePath, 0777, true);
                }
                if (!is_dir($savePath) || !is_writeable($savePath)) {
                    throw new \Exception('无法保存');
                }
            }

            //1、创建画布资源
            // 背景尺寸: 750 * 1334
            $defBga     = app()->getRootPath().'public/static/images/poster-bg1.png';
            $srcBga     = empty($bgImg) ? $defBga : $bgImg;
            $bgInfo     = @getimagesize($srcBga);
            if ($bgInfo[0] != 750 || $bgInfo[1] != 1334) {
                throw new \Exception('海报模板尺寸不正确!');
            }

            if (!$bgInfo) {
                throw new \Exception('海报背景图资源不存在!');
            }

            $ext        = $bgInfo['mime'];
            $img        = null;
            switch ($ext) {
                case 'image/jpeg':
                    $img = @imagecreatefromjpeg($srcBga);
                    break;
                case 'image/png':
                    $img = @imagecreatefrompng($srcBga);
                    break;
            }
            if (!$img) {
                throw new \Exception('无效背景图');
            }

            //2、准备颜色
            $black = imagecolorallocate($img,0,0,0);
            $while = imagecolorallocate($img,255,255,255);
            $faColor = imagecolorallocate($img,0,104,51);

            //填充画布(背景色)
            imagefill($img,0,0, $while);

            // 组合二维码图片 ,坐标:x:246; y:959
            $prefixPng = 'data:image/png;base64,';
            $qrStr = base64_decode(str_replace($prefixPng,"",$srcQr));
            $qrImg = @imagecreatefromstring($qrStr);
            list($qrWidth, $qrHeight) = getimagesize($srcQr);
            if(!$qrImg) {
                imagedestroy($img);
                throw new \Exception('无效二维码');
            }
            $imgQrW = $imgQrH = 274;
            imagecopyresampled($img, $qrImg, 456, 959, 0, 0, $imgQrW, $imgQrH, $qrWidth, $qrHeight);
            imagedestroy($qrImg);
            //4、输出与保存最终图像(保存文件或返回base64)


            if (empty($savePath)) {
                /* 返回base64 */
                ob_start();
                if ($ext == 'image/jpeg') {
                    imagejpeg($img);
                } else {
                    imagepng($img);
                }

                $imgData = ob_get_contents();
                ob_end_clean();
                imagedestroy($img);

                $prefix = 'data:image/jpg/png/gif;base64,';
                return $prefix.base64_encode($imgData);

            } else {
                /* 保存到文件*/
                $fileName = md5(microtime(true)).'.'.$ext;
                $saveFile = $savePath."/".$fileName;
                if ($ext == 'image/jpeg') {
                    imagejpeg($img, $saveFile);
                } else {
                    imagepng($img, $saveFile);
                }
            }

            /*
             *  输出显示
                header("content-type: image/png");
                imagepng($img);
             */

            //5、释放画布资源
            imagedestroy($img);
        } catch (\Exception $e) {
            throw $e;
        }

        return true;
    }
}