Image.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace app\common\service\watermark\image;
  3. use Grafika\Color;
  4. use Grafika\Grafika;
  5. use Grafika\ImageType;
  6. class Image
  7. {
  8. /**
  9. * [waterMark]
  10. *
  11. * @Author: Yeshihao
  12. * @DateTime: 2023/11/14 14:45
  13. * @param $filePath //文件路径
  14. * @param $waterText //水印文字
  15. * @param int $type 0不倾斜 1倾斜
  16. * @return bool
  17. * @throws
  18. */
  19. public function waterMark($filePath, $waterText, $type = 0)
  20. {
  21. // 1 打开海报背景图
  22. $editor = Grafika::createEditor(['Gd']);
  23. $editor->open($backdropImage, $filePath);
  24. // 获取背景图宽高
  25. $size = getimagesize($filePath);
  26. //获取文字类型路劲
  27. $fontPath = Grafika::fontsDir().DS.'st-heiti-light.ttc';
  28. //获取文字数量
  29. $fontNum = mb_strlen($waterText);
  30. // 3.创建文字图片
  31. //判断是否需要添加水印
  32. if ($type) {
  33. //获取斜边长度
  34. $hypo = hypot($size[0], $size[1]);
  35. // 判断文字图片开始的位置
  36. $fontSize = intval($hypo) / $fontNum * 0.5;
  37. // 获取文字大小宽高
  38. $fontSizeArr = $this->get_text_box($waterText, $fontSize, $fontPath);
  39. $fontX = intval(($size[0] * (($hypo - $fontSizeArr[0]) / 2)) / $hypo);
  40. $fontY = intval(($size[1] * (($hypo - $fontSizeArr[0]) / 2)) / $hypo);
  41. //计算倾斜角度
  42. $angle = intval(atan($size[1] / $size[0]) * 180 / pi());
  43. $image = imagecreatetruecolor($size[0], $size[1]);
  44. } else {
  45. // 判断文字图片开始的位置
  46. $fontSize = $size[0] / $fontNum * 0.7;
  47. // 获取文字大小宽高
  48. $fontSizeArr = $this->get_text_box($waterText, $fontSize, $fontPath);
  49. $fontX = 0;
  50. $fontY = 0;
  51. $angle = 0;
  52. $image = imagecreatetruecolor($fontSizeArr[0], $fontSizeArr[1]);
  53. }
  54. imagesavealpha($image, true);
  55. // 设置透明度
  56. $frontImageSource = imagecolorallocatealpha($image, 0, 0, 0, 127);
  57. imagefill($image, 0, 0, $frontImageSource);
  58. //生成文字透明背景板
  59. $fontImage = new \Grafika\Gd\Image($image, '', imagesx($image), imagesy($image), ImageType::PNG);
  60. //设置文字颜色
  61. $Color = new Color('#C0C0C0');
  62. $editor->text($fontImage, $waterText, $fontSize, $fontX, $fontY, $Color, $fontPath, -$angle);
  63. //合并图片
  64. $editor->blend($backdropImage, $fontImage, 'overlay', 1, 'center');
  65. // 保存图片
  66. $editor->save($backdropImage, $filePath);
  67. return true;
  68. }
  69. /**
  70. * [get_text_box]
  71. * 根据文字获取宽高
  72. *
  73. * @Author: Yeshihao
  74. * @DateTime: 2023/11/14 10:04
  75. * @param $text
  76. * @param $size
  77. * @param $font
  78. * @return array
  79. */
  80. private function get_text_box($text, $size, $font)
  81. {
  82. $point = imagettfbbox($size, 0, $font, $text);
  83. $width = $point[4] - $point[6];
  84. $height = $point[1] - $point[7];
  85. return [$width, $height];
  86. }
  87. }