ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# GD 绘制水印 ## 文字水印 ``` <?php /** * @param string $file_name 文件名 * @param string $font_file 字体文件 * @param string $text 水印文字 * @param string $dest_path 水印保存地址 * @param string $prefix 保存文件前缀 * @param int $r 水印颜色 Red * @param int $g 水印颜色 Green * @param int $b 水印颜色 Blue * @param int $alpha 水印颜色 Alpha * @param int $angle 水印角度 * @param int $x 水印所在图片 x 位置 * @param int $y 水印所在图片 y 位置 * @param int $size 水印文字大小 * @param bool $delete_source 是否删除源文件 * @return string */ function water_text($file_name, $font_file, $text = 'webfad', $dest_path = 'watertext', $prefix = 'watertext_', $r = 255, $g = 0, $b = 0, $alpha = 80, $angle = 0, $x = 0, $y = 30, $size = 30,$delete_source = false) { $file_info = getImageInfo($file_name); $image = $file_info['create_fun']($file_name); $color = imagecolorallocatealpha($image, $r, $g, $b, $alpha); imagettftext($image, $size, $angle, $x, $y, $color, $font_file, $text); if ($dest_path && !(file_exists($dest_path))) { mkdir($dest_path, 0777, true); } $dest_name = "{$prefix}{$file_info['file_name']}" . $file_info['extension']; $destination = $dest_path ? $dest_path . "/" . $dest_name : $dest_name; $file_info['out_fun']($image, $destination); if($delete_source) { @unlink($file_name); } imagedestroy($image); return $destination; } /** * @param $filename string 文件名 * @return array */ function getImageInfo($filename) { if (!$info = getimagesize($filename)) { exit('文件不是真实图片!'); } $file_info['file_name'] = pathinfo($filename)['filename']; $file_info['width'] = $info[0]; $file_info['height'] = $info[1]; $mime = image_type_to_mime_type($info[2]); $file_info['extension'] = image_type_to_extension($info[2], true); $file_info['create_fun'] = str_replace('/', 'createfrom', $mime); $file_info['out_fun'] = str_replace('/', '', $mime); return $file_info; } ``` 调用示例 ``` water_text('./images/image.jpg', './fonts/PingFang.ttc'); ``` ## 图片水印 简单 `imagecopymerge()` 函数使用。 ``` <?php $logo = 'images/logo.png'; $file_name = 'images/jd.jpg'; $dst_image = imagecreatefromjpeg($file_name); $src_image = imagecreatefrompng($logo); imagecopymerge($dst_image, $src_image, 0, 0, 0, 0, 190, 170, 60); header('Content-Type: image/jpg'); imagejpeg($dst_image); imagedestroy($dst_image); imagedestroy($src_image); ```