CosService.php 15.9 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 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
<?php

namespace App\Services;

use App\Exceptions\InquiryFilterException;
use App\Models\File\ImageSetting;
use App\Utils\LogUtils;
use Illuminate\Support\Str;
use Qcloud\Cos\Client;
/**
 * @remark :对象存储cos
 * @class  :CosService.php
 * @author :lyh
 * @time   :2023/7/19 15:09
 */
class CosService
{

    /**
     * @param $file
     * @remark :上传图片
     * @name   :uploadFile
     * @author :lyh
     * @method :post
     * @time   :2023/7/19 15:28
     */
    public function uploadFile(&$files, $path, $filename, $binary = false, $watermarkOptions = '')
    {
        $cos = config('filesystems.disks.cos');
        $cosClient = new Client([
            'region' => $cos['region'],
            'credentials' => [
                'secretId' => $cos['credentials']['secretId'],
                'secretKey' => $cos['credentials']['secretKey'],
            ],
        ]);

        $key = $path . '/' . $filename;

        // 判断是否为 Base64 编码的图片流文件
        if (Str::startsWith($files, 'data:image')) {
            // 分离 Base64 头部和数据部分
            [$meta, $base64Data] = explode(',', $files);
            // 解码 Base64 数据
            $Body = base64_decode($base64Data);
            if ($Body === false) {
                outMessage('upload_images',"解码失败");
                return false;
            }
        } else {
            // 如果不是 Base64 流文件,处理为普通文件上传
            try {
                $Body = $binary ? $files : fopen($files->getRealPath(), 'r');
                // 检查文件是否有效
                if (!$Body) {
                    outMessage('upload_images',"文件打开失败");
                    return false;
                }
            } catch (\Exception $e) {
                outMessage('upload_images',"文件处理失败: " . $e->getMessage());
                return false;
            }
        }
        try {
            $options = [
                'Bucket' => $cos['bucket'],
                'Key' => $key,
                'Body' => $Body,
            ];
            // 水印处理
            if ($watermarkOptions) {
                $options['PicOperations'] = json_encode([
                    'is_pic_info' => 1,
                    'rules' => [
                        [
                            'fileid' => $key, // 使用相同的文件名保存
                            'rule' => $watermarkOptions,
                        ]
                    ]
                ], true);
            }
            $cosClient->putObject($options);
        } catch (\Exception $e) {
            // 记录上传失败日志
            outMessage('upload_images',$e->getMessage());
            return false;
        } finally {
            // 确保非二进制模式下关闭文件资源
            if (!$binary && is_resource($Body)) {
                fclose($Body);
            }
        }
        return $key;
    }


    /**
     * @param $image_name
     * @remark :获取图片访问链接
     * @name   :getImageUrl
     * @author :lyh
     * @method :post
     * @time   :2023/7/19 16:08
     */
    public function getImageUrl($image_name)
    {
        $cos = config('filesystems.disks.cos');
        $cosClient = new Client([
            'region' => $cos['region'],
            'credentials' => [
                'secretId' => $cos['credentials']['secretId'],
                'secretKey' => $cos['credentials']['secretKey'],
            ],
        ]);
        $imageUrl = $cosClient->getObjectUrl($cos['bucket'], trim($image_name,'/'), '+10 years');
        return $imageUrl;
    }


    /**
     * 根据远程图片地址上传
     * @param $project_id
     * @param $image_type
     * @param $file_url
     * @param $key
     * @param $body_str
     * @param int $same_name 是否保持名称一直
     * @return string
     * @author Akun
     * @date 2023/09/21 9:39
     */
    public static function uploadRemote($project_id,$image_type,$file_url,$key='',$body_str='',$same_name=0)
    {
        if(!$key){
            $url_arr = parse_url($file_url);
            if($same_name){
                $path_arr = explode('/',$url_arr['path']);
                $filename = end($path_arr);
            }else{
                $ext = explode('.',$url_arr['path']);

                $filename = uniqid().rand(10000,99999).'.'.end($ext);
            }

            $uploads = config('upload.default_file');
            $path = $uploads['path_b'].'/'.$project_id.'/'.$image_type.'/'.date('Y-m');
            $key = $path.'/'.$filename;
        }

        $cos = config('filesystems.disks.cos');
        $cosClient = new Client([
            'region' => $cos['region'],
            'credentials' => [
                'secretId' => $cos['credentials']['secretId'],
                'secretKey' => $cos['credentials']['secretKey'],
            ],
        ]);
        if(empty($body_str)){
            try {
                $body_str = curl_c($file_url,false);
                if(!$body_str){
                    $body_str = file_get_contents($file_url);
                }
            }catch (\Exception $e){
                $body_str = '';
            }
        }

        if(!$body_str){
            return '';
        }
        try {
            $cosClient->putObject([
                'Bucket' => $cos['bucket'],
                'Key' => $key,
                'Body' => $body_str,
            ]);
            return $key;
        }catch (\Exception $e){
            LogUtils::error('uploadRemote error', $e->getMessage());
            return '';
        }
    }

    /**
     * @param $file
     * @return array
     * @throws \Exception
     * @author zbj
     * @date 2023/12/12
     */
    public function checkInquiryFile($file){
        $size = $file->getSize();
        if($size/1024/1024 > 20){
            throw new InquiryFilterException('Your file size exceeds the limit. Please upload a file no larger than 20MB.');
        }
        $extension = $file->getClientOriginalExtension();
//        JPEG (JPG)  PDF  DWG  STEP(STP)IGS word xlsx
        if(!in_array(strtolower($extension), ['png','jpg','jpeg', 'pdf', 'dwg', 'step', 'stp', 'igs','doc','docx','xls','xlsx'])){
            throw new InquiryFilterException('Please upload file in png, jpg, jpeg, pdf, dwg, step, stp, igs, doc, docx, xls or xlsx format.');
        }
        return [
            'size' => $size,
            'extension' => $extension,
            'name' =>  $file->getClientOriginalName(),
            'mime' =>  $file->getMimeType(),
        ];
    }


    /**
     * @remark :生成带水印的图片文件
     * @name   :addFieldImage
     * @author :lyh
     * @method :post
     * @time   :2024/8/19 11:01
     *   gravity/SouthEast:
            gravity:表示水印的对齐方式。常见的值有:
            NorthWest:左上角
            North:顶部中间
            NorthEast:右上角
            West:左侧中间
            Center:中心
            East:右侧中间
            SouthWest:左下角
            South:底部中间
            SouthEast:右下角
     */
    public function setWatermark($cdnUrl = '',$data = [],$is_image = false){
        $domain = 'http://globalso-v6-1309677403.cos.ap-hongkong.myqcloud.com';//cos域名
        $url = $domain . $cdnUrl;
        if($is_image){
            $param = [
                'image/'.urlSafeBase64Encode($domain.$data['image'] ?? ''),//图片
                'gravity/'.($data['gravity'] ?? 'southeast'),
                'dx/'.($data['dx'] ?? 0),
                'dy/'. ($data['dy'] ?? 0),
                'batch/'.($data['batch'] ?? 0),//平铺水印功能
                'dissolve/'.($data['dissolve'] ?? 50),//透明度
                'degree/'.($data['degree'] ?? 0),//旋转角度设置,取值范围为0 - 360,默认0
            ];
            $url = $url.'?watermark/1/'.implode('/',$param);
        }else{
            $param = [
                'text/'.urlSafeBase64Encode($data['text'] ?? ''),//文字水印名称
                'gravity/'.($data['gravity'] ?? 'southeast'),
                'dx/'.($data['dx'] ?? 10),
                'dy/'. ($data['dy'] ?? 10),
                'font/'.urlSafeBase64Encode($data['font'] ?? 'tahoma.ttf'),//默认宋体
                'fontsize/'.($data['fontsize'] ?? 24),//水印文字字体大小,单位为磅,缺省值13
                'fill/'.urlSafeBase64Encode($data['fill'] ?? '#3D3D3D'),//颜色
                'dissolve/'.($data['dissolve'] ?? 50),//透明度
                'degree/'.($data['degree'] ?? 0),//文字水印的旋转角度设置,取值范围为0 - 360,默认0
                'batch/'.($data['batch'] ?? 0),//平铺水印功能
                'shadow/'.($data['shadow'] ?? 0),//文字阴影效果,有效值为[0,100],默认为0,表示无阴影
            ];
            $url = $url.'?watermark/2/'.implode('/',$param);
        }
        return $url;
    }



    /**
     * @remark :添加水印后保存图片(覆盖/非覆盖的文件未存入数据库)
     * @name   :uploadImages
     * @author :lyh
     * @method :post
     * @time   :2024/8/19 17:06
     */
    public function coverOriginalImage($url,$cdnUrl){
        // 获取水印后的图片内容
        $imageContent = file_get_contents($url);
        // 使用 COS SDK 将图片重新上传并覆盖原图
        $cos = config('filesystems.disks.cos');
        $cosClient = new Client([
            'region' => $cos['region'],
            'credentials' => [
                'secretId' => $cos['credentials']['secretId'],
                'secretKey' => $cos['credentials']['secretKey'],
            ],
        ]);
        // 上传并覆盖原图
        $cosClient->putObject([
            'Bucket' => $cos['bucket'],
            'Key' => $cdnUrl, // 去掉域名部分,得到存储桶内的路径
            'Body' => $imageContent,
        ]);
        return $cos['cdn'].$cdnUrl;
    }

    /**
     * @remark :处理9宫格数据
     * @name   :getPosition
     * @author :lyh
     * @method :post
     * @time   :2024/8/19 15:16
     */
    public function getPosition(){
        return [
            1=>'northWest',
            2=>'north',
            3=>'northEast',
            4=>'west',
            5=>'center',
            6=>'east',
            7=>'southWest',
            8=>'south',
            9=>'southEast',
        ];
    }

    /**
     * @remark :字体
     * @name   :getFont
     * @author :lyh
     * @method :post
     * @time   :2024/8/19 15:47
     */
    public function getFont(){
        return [
            'simfang仿宋.ttf',
            'tahoma.ttf',
            'simhei黑体.ttf',
            'simkai楷体.ttf',
            'simsun宋体.ttc',
            'STHeiti Light华文黑体.ttc',
            'STHeiti Medium.ttc',
            '幼圆.TTF',
            'ahronbd.ttf',
            'arial.ttf',
            'ariblk.ttf',
            'Helvetica.dfont',
            'HelveticaNeue.dfont'
        ];
    }

    /**
     * @remark :获取cos图片高度
     * @name   :getImageHeight
     * @author :lyh
     * @method :post
     * @time   :2025/5/8 10:58
     * @param  :pathUrl->存储桶相对路径
     */
    public function getImageHeight($pathUrl){
        $cos = config('filesystems.disks.cos');
        $url = 'https://' . $cos['bucket'] . '.cos.' . $cos['region'] . '.myqcloud.com/' . ltrim($pathUrl, '/') . '?image/info';
        $imageInfo = @getimagesize($url);
        if ($imageInfo) {
//            $width = $imageInfo[0];
            $height = $imageInfo[1];
            return $height;
        }
        return '';
    }

    /**
     * @remark :裁剪图片
     * @name   :cropCosImage
     * @author :lyh
     * @method :post
     * @time   :2025/5/8 11:06
     */
    public function cropCosImage($cosUrl,$height = 220)
    {
        $cos = config('filesystems.disks.cos');
        $cosClient = new Client([
            'region' => $cos['region'],
            'credentials' => [
                'secretId' => $cos['credentials']['secretId'],
                'secretKey' => $cos['credentials']['secretKey'],
            ],
        ]);
        $pathInfo = pathinfo($cosUrl);
        $newKey = $pathInfo['dirname'] . '/crop_' . $pathInfo['filename'] .'.'. $pathInfo['extension'];
        $operations = [
            'is_pic_info' => 0,
            'rules' => [
                [
                    // 注意 fileid 要 base64 编码,并与 Key 相同才能覆盖
                    'fileid' => $newKey,
                    'rule' => 'imageMogr2/crop/x'.$height.'/gravity/center'
                ]
            ]
        ];
        // 执行裁剪并覆盖
        $res = $cosClient->ImageProcess([
            'Bucket' => $cos['bucket'],
            'Key' => $cosUrl, // 要处理的对象路径
            'PicOperations' => json_encode($operations),
        ]);
        if($res){
            return [
                'path' => '/'.$res['ProcessResults']['Object'][0]['Key'] ?? '',
                'size' => (int)$res['ProcessResults']['Object'][0]['Size'] ?? 0,
                'mime' => 'image/'.($res['ProcessResults']['Object'][0]['Format'] ?? 'jpg'),
                'type' => $res['ProcessResults']['Object'][0]['Format'] ?? 'jpg',
            ];
        }
        return [];
    }

    /**
     * @remark :ai_video裁剪图片为4张
     * @name   :cropAndUploadToCOS
     * @author :lyh
     * @method :post
     * @time   :2025/8/2 16:52
     */
    public function cropAndUploadToCOS($imageUrl)
    {
        // 1. 下载远程图片内容
        $imageData = file_get_contents($imageUrl);
        if (!$imageData) {
            return false;
        }
        // 2. 保存原图到临时文件
        $tempOriginal = tempnam(sys_get_temp_dir(), 'original_') . '.png';
        file_put_contents($tempOriginal, $imageData);
        // 3. 使用 GD 加载图像
        $src = imagecreatefrompng($tempOriginal);
        if (!$src) {
            return false;
        }
        $width = imagesx($src);
        $height = imagesy($src);
        $halfWidth = intval($width / 2);
        $halfHeight = intval($height / 2);
        // 4. 从原图 URL 提取路径信息
        $parsed = parse_url($imageUrl);
        $pathInfo = pathinfo($parsed['path']); // upload/p/1/png/2025-08/688dcebc26a7a59911.png
        $cosPath = ltrim($pathInfo['dirname'], '/'); // 相对路径:upload/p/1/png/2025-08
        $baseName = $pathInfo['filename'];           // 文件名:688dcebc26a7a59911
        $ext = $pathInfo['extension'] ?? 'png';      // 扩展名
        // 5. 初始化 COS 客户端
        $cos = config('filesystems.disks.cos');
        $cosClient = new Client([
            'region' => $cos['region'],
            'credentials' => [
                'secretId' => $cos['credentials']['secretId'],
                'secretKey' => $cos['credentials']['secretKey'],
            ],
        ]);
        // 6. 循环裁剪并上传
        $resultPaths = [];
        $index = 0;
        $cos = config('filesystems.disks.cos');

        for ($y = 0; $y < 2; $y++) {
            for ($x = 0; $x < 2; $x++) {
                $crop = imagecreatetruecolor($halfWidth, $halfHeight);
                imagecopy($crop, $src, 0, 0, $x * $halfWidth, $y * $halfHeight, $halfWidth, $halfHeight);
                $tempCropped = tempnam(sys_get_temp_dir(), 'crop_') . '.png';
                imagepng($crop, $tempCropped);
                imagedestroy($crop);
                // 新文件名,保持路径不变
                $filename = $baseName . '_part' . $index++ . '.' . $ext;
                $objectKey = $cosPath . '/' . $filename;
                // 上传到 COS
                $cosClient->putObject([
                    'Bucket' => $cos['bucket'],
                    'Key' => $objectKey,
                    'Body' => fopen($tempCropped, 'rb'),
                ]);
                // 返回相对路径
                $resultPaths[] = $cos['cdn1'].'/'.$objectKey;
                unlink($tempCropped);
            }
        }
        // 清理资源
        imagedestroy($src);
        unlink($tempOriginal);
        return $resultPaths; // 相对路径数组
    }
}