PHP GD库文字水印实现原理
文字水印
文字水印技术旨在图像表面叠加文本内容,核心依赖于GD库提供的imagefttext函数,且必须指定有效的字体文件。具体视觉效果参考
。
具体实现逻辑如下所示:
复制代码 代码如下: $dst_path = 'dst.jpg';
//初始化目标图像资源 $dst = imagecreatefromstring(file_get_contents($dst_path));
//执行文字绘制操作 $font = './simsun.ttc';//指定字体路径 $black = imagecolorallocate($dst, 0x00, 0x00, 0x00);//定义黑色字体颜色 imagefttext($dst, 13, 0, 20, 20, $black, $font, '快乐编程');//设置字号、角度、坐标及内容
//根据图像类型输出结果 list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path); switch ($dst_type) { case 1://GIF格式 header('Content-Type: image/gif'); imagegif($dst); break; case 2://JPG格式 header('Content-Type: image/jpeg'); imagejpeg($dst); break; case 3://PNG格式 header('Content-Type: image/png'); imagepng($dst); break; default: break; }
//销毁图像资源以释放内存 imagedestroy($dst);
PHP GD库图片水印叠加方法
图片水印
图片水印是将一幅图像叠加至另一幅图像之上,主要调用GD库中的imagecopy和imagecopymerge函数。效果展示见
。
相关代码实现如下:
复制代码 代码如下: $dst_path = 'dst.jpg'; $src_path = 'src.jpg';
//分别创建目标与源图像的实例 $dst = imagecreatefromstring(file_get_contents($dst_path)); $src = imagecreatefromstring(file_get_contents($src_path));
//获取水印图片的尺寸信息 list($src_w, $src_h) = getimagesize($src_path);
//将水印合并至目标图,参数50代表50%透明度以实现半透明效果 imagecopymerge($dst, $src, 10, 10, 0, 0, $src_w, $src_h, 50); //若需保留原图透明通道,应改用imagecopy方法 //imagecopy($dst, $src, 10, 10, 0, 0, $src_w, $src_h);
//按原始图像格式输出最终结果 list($dst_w, $dst_h, $dst_type) = getimagesize($dst_path); switch ($dst_type) { case 1://GIF格式 header('Content-Type: image/gif'); imagegif($dst); break; case 2://JPG格式 header('Content-Type: image/jpeg'); imagejpeg($dst); break; case 3://PNG格式 header('Content-Type: image/png'); imagepng($dst); break; default: break; }
//同时销毁两个图像资源 imagedestroy($dst); imagedestroy($src);