在代码app/api/behavior/tags.php里面添加
'upload_after' => [ 'app\\api\\behavior\\UploadAfter',//可填写自己命名的文件 ],
return [ 'upload_after' => [ 'app\\api\\behavior\\UploadAfter', ], ];
在代码创建代码在目录模块 app/api/behavior/
文件名UploadAfter.php (要和tags里面的对应哦)
<?php namespace app\api\behavior; use think\image\Exception as ImageException; class UploadAfter { public function run(&$params) { if (request()->action() == 'upload_water_image' || request()->post('type') == 'image_water') { //更具自己的方法或者参数来判断是否要加入水印 这里方法和post参数type 为里面的值即可QQ496631085 he4966.cn // $new_file_name = $uploadDir . $file->getSaveName(); if (in_array($params['mimetype'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) { $image = \think\Image::open('.' . $params['url']); $scene_type = request()->post('type', 'image_water'); $font_path = \think\Config::get('site.water_text'); //水印字体路径 $font_color = \think\Config::get('site.water_color') ?? '#3c3c3c'; //水印文字颜色 switch ($scene_type) { case 'product_thumb': $splInfo = $image->thumb(200, 200)->save('.' . $params['url']); break; case 'product_img': $splInfo = $image->thumb(750, 750)->save('.' . $params['url']); break; case 'product_detail_img': $splInfo = $image->save('.' . $params['url']); break; default: $size = $this->get_text_size($font_path, '.' . \think\Config::get('site.water_font'), 30); $w = $size['w']; $h = $size['h']; for ($w_i = 0; $w_i <= $image->width() / $w; $w_i++) { for ($h_i = 0; $h_i <= $image->height() / $h; $h_i++) { //循环加入文字水印 $image->text($font_path, '.' . \think\Config::get('site.water_font'), 20, $font_color, [$w_i * ($w + 20), $h_i * ($h + 20)], 0, 15); } } $splInfo = $image->save('.' . $params['url']); break; } } else { // $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName); } } } /** * 图像添加文字 * * @param string $text 添加的文字 * @param string $font 字体路径 * @param integer $size 字号 * * @return $this * @throws ImageException */ public function get_text_size($text, $font, $size) { if (!is_file($font)) { throw new ImageException("不存在的字体文件:{$font}"); } //获取文字信息 $info = imagettfbbox($size, 0, $font, $text); $minx = min($info[0], $info[2], $info[4], $info[6]); $maxx = max($info[0], $info[2], $info[4], $info[6]); $miny = min($info[1], $info[3], $info[5], $info[7]); $maxy = max($info[1], $info[3], $info[5], $info[7]); /* 计算文字初始坐标和尺寸 */ $x = $minx; $y = abs($miny); $w = $maxx - $minx; $h = $maxy - $miny; return ['w' => $w, 'h' => $h]; } }
然后就可以写个接口方法名为
upload_water_image
示例/api/com/upload_water_image