1
0

tools.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: vien
  5. * Date: 2019/3/27
  6. * Time: 10:38 AM
  7. */
  8. /**
  9. * @func 时间戳格式化
  10. * @param $timestamp
  11. * @return false|string
  12. */
  13. function vn_time($timestamp)
  14. {
  15. return date('Y-m-d H:i:s', $timestamp);
  16. }
  17. function watermark($imgPath, $savePath, $str)
  18. {
  19. $ext = strtolower(pathinfo($imgPath, PATHINFO_EXTENSION));
  20. if ($ext == "png") {
  21. $im = imagecreatefrompng($imgPath);
  22. } else if (in_array($ext, ['jpeg', 'jpg'])) {
  23. $im = imagecreatefromjpeg($imgPath);
  24. } else {
  25. // 格式不是png和jpg不加水印
  26. return;
  27. }
  28. // 载入字体zt.ttf
  29. $fnt = resource_path("/fonts/fzsj.ttf");
  30. // 文字相对于高度或者宽度的比例
  31. $scale = 0.04;
  32. // 设置颜色,用于文字字体的白和阴影的黑
  33. $white=imagecolorallocate($im,255,255,255);
  34. $black=imagecolorallocate($im,50,50,50);
  35. // 计算文字大小和位置
  36. $imgInfo = getimagesize($imgPath);
  37. $width = $imgInfo[0];
  38. $height = $imgInfo[1];
  39. $textSize = ($height + $width) / 2 * $scale;
  40. $bbox = imagettfbbox($textSize, 0, $fnt, $str);
  41. $textWidth = abs($bbox[2] - $bbox[0]);
  42. $textHeight = abs($bbox[3] - $bbox[5]);
  43. $top = $height - $textHeight / 1.8;
  44. $left = $width - $textSize - $textWidth;
  45. // 超出画幅不加水印
  46. if ($top < 0 || $left < 0) return;
  47. //在图片中添加文字,imagettftext (image,size,angle, x, y,color,fontfile,text)
  48. imagettftext($im,$textSize, 0, $left+1, $top+1, $black, $fnt, $str);
  49. imagettftext($im,$textSize, 0, $left, $top, $white, $fnt, $str);
  50. //将$im输出
  51. ImageJpeg($im, $savePath);
  52. //销毁$im对象
  53. ImageDestroy($im);
  54. }