Drawer.php 13.6 KB
Newer Older
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
<?php
/**
 * Created by PhpStorm.
 * User: Zero
 * Date: 2020/7/27
 * Time: 11:44
 */

namespace Meibuyu\Micro\Tools;

use Exception;
use Hyperf\Contract\ConfigInterface;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class Drawer
{

    /**
     * @var ConfigInterface
     */
    protected $config;

    private $rootPath;

    private $savePath = '';

28 29
    private $ossDomain = 'http://huaperfect-file-service.oss-cn-hangzhou.aliyuncs.com';

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
    public function __construct()
    {
        $this->config = container(ConfigInterface::class);
        $this->rootPath = $this->config->get('server.settings.document_root', BASE_PATH . '/public');
    }

    private function parseImagePath($imagePath)
    {
        if (strstr($imagePath, 'http') !== false) {
            $imagePath = $this->downloadWebImage($imagePath);
        }
        return $imagePath;
    }

    /**
45
     * 下载网络图片
46 47 48 49 50 51
     * @param string $url
     * @param string $path
     * @return string
     */
    public function downloadWebImage($url, $path = null)
    {
52
        $url = $this->parseUrl($url);
53
        // excel画图中下载图片时对图片名做urlencode处理,防止中文名不能正常画图片的bug
54 55 56
        $pathinfo = pathinfo($url);
        $filename = trim($pathinfo['filename']);
        $ext = strtolower($pathinfo['extension']);
57
        $filename = "$filename.$ext";
58 59
        $savePath = $this->parseSavePath($pathinfo['dirname'], $path);
        if (!is_dir($savePath)) {
60
            // 判断路径是否存在,不存在,则创建
61
            mkdir($savePath, 0777, true);
62
        }
63
        $filePath = $savePath . '/' . $filename;
64 65 66 67 68 69 70 71
        if (!file_exists($filePath)) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            $file = curl_exec($ch);
            curl_close($ch);
72
            $resource = fopen($filePath, 'a');
73 74 75 76 77 78 79 80
            fwrite($resource, $file);
            fclose($resource);
        }
        return $filePath;
    }

    private function parseUrl($url)
    {
81 82 83 84
        if (!preg_match('/%[0-9A-Z]{2}/', $url)) {
            $url = rawurlencode($url);
            $url = str_replace("%3A", ":", $url);
            $url = str_replace("%2F", "/", $url);
王源's avatar
王源 committed
85 86
            $url = str_replace("%3F", "?", $url);
            $url = str_replace("%3D", "=", $url);
87
            $url = str_replace("%26", "&", $url);
88
        }
89
        return $this->handleOssUrl($url);
90 91
    }

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    /**
     * 处理保存路径
     * @param $dirname
     * @param $path
     * @return string
     * @author Zero
     */
    private function parseSavePath($dirname, $path)
    {
        $path = trim($path, '/');
        $path = $this->rootPath . '/download/images/' . ($path ?: $this->savePath) . '/';
        if (strstr($dirname, $this->ossDomain) !== false) {
            // 以oss的原路径为保存路径
            $dirname = str_replace($this->ossDomain, '', $dirname);
            $dirname = trim($dirname, '/');
            $path = $path . $dirname . '/';
        }
        return $path;
    }

112 113 114 115
    // 替换阿里云图片内部地址
    private function handleOssUrl($url)
    {
        if ($this->config->get('app_env') !== 'dev') {
王源's avatar
王源 committed
116
            $url = str_replace('oss-cn-hangzhou.aliyuncs.com', 'oss-accelerate.aliyuncs.com', $url);
王源's avatar
王源 committed
117
            $this->ossDomain = 'http://huaperfect-file-service.oss-accelerate.aliyuncs.com';
118 119 120
        }
        return $url;
    }
121 122 123 124 125 126 127 128 129 130 131 132

    /**
     * description:下载文件到服务端 增加判断是否是webp 格式的图片处理
     * author: fuyunnan
     * @param string $url
     * @param string $path 文件路径
     * @return string
     * @throws
     * Date: 2020/11/20
     */
    public function downLoadImgWebpChannel($url, $path = '')
    {
133
        $originUrl = $url;
134
        //如果shopify 去掉版本号
135
        if (strpos($url, 'shopify') !== false && strpos($url, '?v=') !== false) {
136
            $url = substr($url, 0, strpos($url, '?v='));
137
            var_dump($url);
138 139 140 141 142 143 144 145 146 147
        }
        $savePath = $this->rootPath . '/download/images/' . ($path ? $path . '/' : $this->savePath);
        create_file_dir($savePath);
        $filePath = $this->toWebpImg($url, $savePath);
        if (!file_exists($filePath)) {
            $filename = trim(pathinfo($url, PATHINFO_FILENAME));
            $ext = strtolower(pathinfo($url, PATHINFO_EXTENSION));
            $filePath = $savePath . "$filename.$ext";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
148
            curl_setopt($ch, CURLOPT_URL, $originUrl);
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
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
            $file = curl_exec($ch);
            curl_close($ch);
            $resource = fopen($filePath, 'a');
            fwrite($resource, $file);
            fclose($resource);
            $filePath = $this->toWebpImg($filePath, $savePath);
        }
        return $filePath;
    }

    /**
     * description:将图像绘到excel表格上
     * author: fuyunnan
     * @param string $url 图片地址
     * @param string $childPath 图片地址 用sku名作为文件夹名称
     * @param int $h 图片高度
     * @param string $p 单元格索引
     * @param Worksheet $sheet
     * @return void
     * @throws
     * Date: 2020/11/23
     */
    public function drawImgExcel($url, $childPath, $h, $p, $sheet)
    {
        try {
            //下载图片到本地
177
            $absPath = $this->downLoadImgWebpChannel($url, $childPath);
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
            $drawing = new Drawing();
            $drawing->setPath($absPath)
                ->setCoordinates($p)
                ->setHeight($h)
                ->setOffsetX(1)
                ->setOffsetY(1)
                ->setWorksheet($sheet);
        } catch (Exception $e) {
            put_log($e->getMessage(), 'draw2Excel.log');
        }
    }

    /**
     * description:检查文件是否是webp格式的文件
     * 如果是,转化为jpeg格式的文件,并且返回文件的绝对地址.
     * author: fuyunnan
     * @param string $filePath 文件的绝对地址
     * @param string $savePath 文件重新保存的地址
     * @return string
     * @throws
     * Date: 2020/11/23
     */
    private function toWebpImg($filePath, $savePath)
    {
        $filename = trim(pathinfo($filePath, PATHINFO_FILENAME));
        $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
        $imgInfo = '';

        //如果存在直接返回 防止每次获取文件资源
        if (file_exists($savePath . "$filename.$ext")) {
            return $savePath . "$filename.$ext";
        }
        $filePath && $imgInfo = getimagesize($filePath);
        if ($imgInfo && end($imgInfo) == "image/webp") {
            $filename = trim(pathinfo($filePath, PATHINFO_FILENAME));
            $im = imagecreatefromwebp($filePath); // 加载 WebP 文件
214
            switch ($ext) {
215 216 217 218 219 220 221 222 223 224 225 226 227 228
                case 'jpg':
                    $toNewFileName = $savePath . $filename . '.jpg';
                    break;
                case 'png':
                    $toNewFileName = $savePath . $filename . '.png';
                    break;
                case 'jpeg':
                    $toNewFileName = $savePath . $filename . '.jpeg';
                    break;
                default:
                    $toNewFileName = $savePath . $filename . '.jpeg';
                    break;
            }
            imagejpeg($im, $toNewFileName, 30);//转化图片比例
229
            imagedestroy($im);
230
            return $toNewFileName;
231 232 233 234
        }
        return $savePath . "$filename.$ext";
    }

235 236 237 238 239 240 241 242 243 244 245 246
    /**
     * @param $imgPath
     * @param int $px
     * @return bool|string
     * @throws Exception
     */
    public function addBoard($imgPath, $px = 2)
    {
        $imgPath = $this->parseImagePath($imgPath);

        $imgPathInfo = pathinfo($imgPath);
        $filename = $imgPathInfo['filename']; // 图片名称
王源's avatar
王源 committed
247 248
        $ext = $this->getImgExt($imgPath);

249 250
        [$img_w, $img_h] = getimagesize($imgPath); // 图片大小

251
        $savePath = $this->rootPath . '/download/board/' . $this->savePath;
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
        if (!is_dir($savePath)) {
            // 判断路径是否存在,不存在,则创建
            mkdir($savePath, 0777, true);
        }
        $imgNewPath = $savePath . '/' . $filename . '.' . $ext;
        if (file_exists($imgNewPath)) {
            return $imgNewPath;
        }

        switch ($ext) {
            case 'jpeg':
            case 'jpg':
                $img_create_func = 'imagecreatefromjpeg';
                $img_save_func = 'imagejpeg';
                break;
            case 'png':
                $img_create_func = 'imagecreatefrompng';
                $img_save_func = 'imagepng';
                break;
            case 'bmp':
                $img_create_func = 'imagecreatefrombmp';
                $img_save_func = 'imagebmp';
                break;
            case 'gif':
                $img_create_func = 'imagecreatefromgif';
                $img_save_func = 'imagegif';
                break;
            case 'vnd.wap.wbmp':
                $img_create_func = 'imagecreatefromwbmp';
                $img_save_func = 'imagewbmp';
                break;
            case 'xbm':
                $img_create_func = 'imagecreatefromxbm';
                $img_save_func = 'imagexbm';
                break;
            default:
                throw new Exception("图片类型不支持");
        }

        // 黑色背景图片
        $im = @imagecreatetruecolor(($img_w + $px), ($img_h + $px)) or die ("Cannot Initialize new GD image stream");
        // 为真彩色画布创建背景,再设置为透明
        $color = imagecolorallocate($im, 0, 0, 0);
        imagefill($im, 0, 0, $color);
        imageColorTransparent($im, $color);
        // 把图片放到黑色背景图片上。边框是1px
        $resource = $img_create_func($imgPath);
        imagecopy($im, $resource, $px / 2, $px / 2, 0, 0, $img_w, $img_h);

        $res = $img_save_func($im, $imgNewPath);

        imagedestroy($im);
        return $res ? $imgNewPath : false;
    }

307 308 309
    /**
     * 拼图
     * @param $imgPathList
310
     * @param string $name
311 312
     * @return bool|string
     */
313
    public function mergeImages($imgPathList, $name = '')
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
    {
        $maxW = $maxH = 0;
        $filenameList = [];
        $imageList = [];
        foreach ($imgPathList as $k => $path) {
            $path = $this->parseImagePath($path);
            $imgPathInfo = pathinfo($path);
            $filename = $imgPathInfo['filename']; // 图片名称
            $ext = $imgPathInfo['extension']; // 图片扩展名
            [$w, $h] = getimagesize($path); // 图片大小
            $imageList[$k] = [
                'path' => $path,
                'filename' => $filename,
                'ext' => $ext,
                'w' => $w,
                'h' => $h,
            ];
            $filenameList[] = $filename;
            $maxW += $w;
            if ($maxH < $h) {
                $maxH = $h;
            }
        }
        $filenameList = collect($filenameList)->unique()->sort()->toArray();
        $filename = implode('_', $filenameList);
        $savePath = $this->rootPath . '/download/merge/' . $this->savePath;
        if (!is_dir($savePath)) {
            // 判断路径是否存在,不存在,则创建
            mkdir($savePath, 0777, true);
        }
344
        $imgNewPath = $savePath . '/' . ($name ?: $filename) . '.png';
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
        if (file_exists($imgNewPath)) {
            return $imgNewPath;
        }
        // 黑色背景图片
        $im = @imagecreatetruecolor($maxW, $maxH) or die ("Cannot Initialize new GD image stream");
        // 为真彩色画布创建背景,再设置为透明
        $color = imagecolorallocate($im, 0, 0, 0);
        imagefill($im, 0, 0, $color);
        imageColorTransparent($im, $color);
        // 循环画图片
        $dstX = 0;
        foreach ($imageList as $item) {
            $resource = imagecreatefromstring(file_get_contents($item['path']));
            imagecopy($im, $resource, $dstX, 0, 0, 0, $item['w'], $item['h']);
            $dstX += $item['w'];
        }
        $res = imagepng($im, $imgNewPath);
        imagedestroy($im);
        return $res ? $imgNewPath : false;
    }

366 367 368 369 370 371
    /**
     * 画图片
     * @param string $path 图片路径
     * @param int $h 图片高度
     * @param string $p 单元格索引
     * @param Worksheet $sheet
王源's avatar
王源 committed
372
     * @param int $boardPx
373
     */
王源's avatar
王源 committed
374
    public function draw2Excel($path, $h, $p, $sheet, $boardPx = 0)
375 376 377
    {
        try {
            $path = $this->parseImagePath($path);
王源's avatar
王源 committed
378 379
            if ($boardPx) {
                $path = $this->addBoard($path, $boardPx);
380 381
            }
            $drawing = new Drawing();
382
            $drawing->setPath($path)->setCoordinates($p)->setHeight($h)->setOffsetX(1)->setOffsetY(1)->setWorksheet($sheet);
383
        } catch (Exception $e) {
384
            put_log($e->getMessage(), 'draw2Excel.log');
385 386 387 388 389
        }
    }

    public function setSavePath($path)
    {
390
        $this->savePath = trim($path, '/');
391 392
    }

王源's avatar
王源 committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    /**
     * 获取图片扩展名
     * @param $path
     * @return bool|mixed|string
     * @author Zero
     */
    public function getImgExt($path)
    {
        $ext = false;
        $info = getimagesize($path);
        if (isset($info['mime']) && $info['mime']) {
            $ext = explode('/', $info['mime'])[1];
        } else {
            $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            $ext = explode('?', $ext)[0] ?? $ext;
        }
        return $ext;
    }

412
}