PHP图像字符水印居中

180it 2021-05-28 PM 1664℃ 0条
<?php
//让图像上字符串居中
header("content-type:text/html;charset = utf-8");
//(1)创建画布
$filename = "./images/02.jpg";
$img = imagecreatefromjpeg($filename);
$str = "WELCOME to liuguofeng.com";
$font = 5;
//(2)分配颜色:
$color1 = imagecolorallocate($img,255,0,255);
$color2 = imagecolorallocate($img,255,0,255);
//(3)获取画布宽度和高度
$imgWidth = imagesx($img);
$imgHeight = imagesy($img);
//(4)获取字体尺寸
$fontWidth = imagefontwidth($font);
$fontHeight = imagefontheight($font);
//(5)计算字符串的起始坐标
$x = ($imgWidth-$fontWidth*strlen($str))/2;
$y = ($imgHeight-$fontHeight)/2;
//(6)写入一个字符串
imagestring($img,$font,$x,$y,$str,$color1);
header("content-type:image/jpeg");
imagejpeg($img);
//(7)关闭图像
imagedestroy($img);
?>



//支持中文

$main = imagecreatefromjpeg('./test.jpg');
 
$fontSize = 38;
$width   = imagesx($main);
$height   = imagesy($main);
 
//1.设置字体的路径
$font    = "./t.ttf";
//2.填写水印内容
$content = "My name is Siam,中文是宣言";
//3.设置字体颜色和透明度
$color   = imagecolorallocatealpha($main, 255, 255, 255, 0);
 
$fontBox = imagettfbbox($fontSize, 0, $font, $content);//获取文字所需的尺寸大小 
 
//4.写入文字 (图片资源,字体大小,旋转角度,坐标x,坐标y,颜色,字体文件,内容)
imagettftext($main, $fontSize, 0, ceil(($width - $fontBox[2]) / 2), ceil(($height - $fontBox[1] - $fontBox[7]) / 2), $color, $font, $content);
 
// 浏览器输出 也可以换成保存新图片资源
header("Content-type:jpg");
imagejpeg($main);

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

PHP图像字符水印居中