最近工作中遇到需要把图片加上水印和文字。用了很多种方法。遇到了无数的坑。终于解决了。分享给大家。不喜勿喷。
首先介绍几个方法
imagecopymerge() 函数用于拷贝并合并图像的一部分,成功返回 TRUE ,否则返回 FALSE 。
bool imagecopymerge( resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y,int src_w, int src_h, int pct )
参数说明:
参数
说明
dst_im
目标图像
src_im
被拷贝的源图像
dst_x
目标图像开始 x 坐标
dst_y
目标图像开始 y 坐标,x,y同为 0 则从左上角开始
src_x
拷贝图像开始 x 坐标
src_y
拷贝图像开始 y 坐标,x,y同为 0 则从左上角开始拷贝
src_w
(从 src_x 开始)拷贝的宽度
src_h
(从 src_y 开始)拷贝的高度
pct
图像合并程度,取值 0-100 ,当 pct=0 时,实际上什么也没做,反之完全合并。
imagecopyresampled图像处理函数,缩放图片。
bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
dst_image
目标图象连接资源。
src_image
源图象连接资源。
dst_x
目标 X 坐标点。
dst_y
目标 Y 坐标点。
src_x
源的 X 坐标点。
src_y
源的 Y 坐标点。
dst_w
目标宽度。
dst_h
目标高度。
src_w
源图象的宽度。
src_h
源图象的高度。
imagettftext图像中插入文字
imagettftext( resource $image ,float $size, float$angle, int $x, int $y, int $color, string $fontfile, string $text)
image
目标图象连接资源。
size
字体大小
angle
旋转角度
x
x 坐标点。
y
y坐标点。
color
颜色。
fontfile
字体。
text
内容。
源码:
图片水印:
$srcImg="base.png";
$waterImg= "water.png";
$alpha=100;
$srcImgObj = $this->image_create_from_ext($srcImg);
$waterImgObj = $this->image_create_from_ext($waterImg);
$x = 517; $y = 850;
imagecopymerge($srcImgObj, $waterImgObj, $x, $y, 0, 0, 315, 315,$alpha);
图片缩放(原图片缩放成80*80):
$waterImgObj = $this->image_create_from_ext($waterImg);
$img = imagecreatetruecolor(80, 80);
imagefill($img, 0, 0, imagecolorallocate($img, 255, 255, 255));
$srcinfo = @getimagesize($waterImg);
imagecopyresampled($img, $waterImgObj, 0, 0, 0, 0, 80,80, $srcinfo[0], $srcinfo[1]);
文字水印(文字居中显示):
$font = 'simsun.ttc';//字体
$text1=“快乐编程”;
$fontSize = 18;//像素字体
$fontColor = imagecolorallocate ( $srcImgObj, 0, 0, 0 );//字的RGB颜色
$fontBox = imagettfbbox($fontSize, 0, $font, $text1);//文字水平居中实质
imagettftext ( $srcImgObj, $fontSize, 0, ceil((1350 - $fontBox[2]) / 2), 1250, $fontColor, $font, $text1 );