图像处理_02_水印

一  在图片右下角 写入文字水印

<?php
header('content-type:image/jpeg');//1 设置输出图片格式

$image = imagecreatefromjpeg('ldh.jpg');//2 打开一幅本地图片

//创建用到的变量
$waterMarkColor = imagecolorallocatealpha($image,rand(200,255),rand(200,255),rand(200,255),0);//0不透明 127完全透明
$ttfPath = 'G:phpstudy_proWWWwww.sunshengli2.comdemosimsun.ttc';//字体绝对路径
$text = '不老男神';

//获取到大图的宽高
$imageWidth = imagesx($image);
$imageHeight = imagesy($image);
getimagesize('ldh.jpg');//这个函数不能传递资源类型 必须传入图片路径 返回array

//获取到水印文字的尺寸 返回一个数组
$waterMarkArr = imagettfbbox(16,0,$ttfPath,$text) ;//本节重点学习这个函数

//通过 右下角x坐标 减去 左下角的 x坐标  得到水印文字的宽度
$stringWidth = $waterMarkArr[2]-$waterMarkArr[0];

//向页面右下角写入水印
imagettftext($image,16,0,$imageWidth-1-$stringWidth-($imageWidth/100),$imageHeight-1-($imageWidth/100),$waterMarkColor,$ttfPath,$text);
imagejpeg($image);//输出图像 imagedestroy($image);//销毁资源

本小节用到的二个知识点

1)imagestring  和 imagettftext 的区别

  imagestring()

    不能输出汉字

    x轴 和 y轴 定义的是第一个字符的 左上角 例如:左上角为 0 0。

  imagettftext()

    可以设置字体输出汉字

    由 x y 坐标定义的是 字符的 左下角

     y 坐标,它设定了字体基线的位置,而不是字符的最底端

 


2)imagettfbbox()函数的使用:取得使用 TrueType 字体的文本的范围
/*
 * 函数返回包含8个值的数组 代表了文本外框的四个角
* 0 左下角 X 位置 1 * 1 左下角 Y 位置 3 * 2 右下角 X 位置 83 * 3 右下角 Y 位置 3 * 4 右上角 X 位置 83 * 5 右上角 Y 位置 -18 * 6 左上角 X 位置 1 * 7 左上角 Y 位置 -18
*/

 

二 图片水印

<?php
header('content-type:image/jpeg');//1设置输出图片格式

//2 打开需要添加水印的图片
$dst_im = imagecreatefromjpeg('ldh.jpg');
$dst_width = imagesx($dst_im);//取得目标水印图片的宽度
$dst_height = imagesy($dst_im);//取得目标水印的高度

//3 打开水印土图片
$src_im = imagecreatefromgif('water.gif');
$src_width = imagesx($src_im);//获取水印图片的宽度
$src_height = imagesy($src_im);//获取水印图片的高度

//4_1 拷贝图像的一部分
imagecopy($dst_im,$src_im,($dst_width-$src_width)-($dst_width/30),($dst_height-$src_height)-($dst_height/30),0,0,$src_width,$src_height);
//4_2 拷贝并合并图像的一部分
imagecopymerge($dst_im,$src_im,($dst_width-$src_width)-($dst_width/30),($dst_height-$src_height)-($dst_height/30),0,0,$src_width,$src_height,50);

//5 输出图像
imagejpeg($dst_im);
//6 销毁资源
imagedestroy($dst_im);

 

本小节的两个重要函数

imagecopy()

src_im 图像中坐标从 src_xsrc_y 开始,宽度为 src_w,高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_xdst_y 的位置上。

imagecopymerge()

和imagecopy()函数一样,在参数列表末尾多了一个参数,参数取值:0-100   0完全透明  100完全不透明

原文地址:https://www.cnblogs.com/fuyunlin/p/13946839.html