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
| <?php
namespace App\Helper;
use Imagick; use ImagickDraw; use ImagickPixel;
class ImageWatermark { static function applyWatermarkFromUrl($tmpPath, $srcURL,$text="自定义水印", $color = '#050629', $alpha = 0.2, $angle = -24, $space = 0.5, $size = null, $fontFile = null) { $path = parse_url($srcURL, PHP_URL_PATH); $fileInfo = pathinfo($path); $filename = $fileInfo['filename'] . '.' . $fileInfo['extension']; $newFileName = $fileInfo['filename'] . '-water.png'; if (!is_dir($tmpPath)) { if (!mkdir($tmpPath, 0755, true)) { throw new \Exception("创建目录失败" . $tmpPath); } } $content = @file_get_contents($srcURL); if ($content === false) { throw new \Exception("获取远程文件失败" . $srcURL); } $oldFileName = $tmpPath . $filename; if (file_put_contents($oldFileName, $content) === false) { throw new \Exception("下载远程文件失败 " . $srcURL); } $savePath = $tmpPath . $newFileName; return self::applyWatermark($oldFileName, $savePath, $text, $color, $alpha, $angle, $space, $size, $fontFile); }
static function applyWatermark($srcImage, $savePath = null, $text="自定义水印", $color = '#050629', $alpha = 0.3, $angle = -24, $space = 0.5, $size = null, $fontFile = null) { if (!file_exists($srcImage)) { throw new \Exception("文件不存在 " . $srcImage); } $im = new Imagick($srcImage); $width = $im->getImageWidth(); $height = $im->getImageHeight(); $draw = new ImagickDraw(); if (!$fontFile) $fontFile = __DIR__ . '/AlibabaPuHuiTi-3-105-Heavy.ttf'; if (!file_exists($fontFile)) { throw new \Exception("字体不存在 " . $fontFile); } if (is_null($size)) { $size = max(4, min($width, $height) / 30); } $draw->setFont($fontFile); $draw->setFontSize($size); $draw->setFillColor(new ImagickPixel(sprintf( 'rgba(%d,%d,%d,%f)', hexdec(substr($color, 1, 2)), // 红色 hexdec(substr($color, 3, 2)), // 绿色 hexdec(substr($color, 5, 2)), // 蓝色 $alpha // 透明度 )));
$metrics = $im->queryFontMetrics($draw, $text); $textWidth = $metrics['textWidth']; $textHeight = $metrics['textHeight'];
$rad = deg2rad(abs($angle)); $rotW = $textWidth * cos($rad) + $textHeight * sin($rad); $rotH = $textWidth * sin($rad) + $textHeight * cos($rad);
$hSpacing = $rotW + 5; $vSpacing = $rotH * $space;
$cols = ceil($width / $hSpacing); $rows = ceil($height / $vSpacing);
for ($i = 0; $i <= $cols; $i++) { for ($j = 0; $j <= $rows; $j++) { $x = $i * $hSpacing; $y = $j * $vSpacing; $im->annotateImage($draw, $x, $y, $angle, $text); } }
if ($savePath) { $im->setImageFormat('png'); $im->writeImage($savePath); $im->destroy(); return $savePath; } else { header('Content-Type: image/png'); echo $im; $im->destroy(); exit; }
} }
|