以内容标题文字,渲染在随机的背景图片内,生成为一张全新的图片进行展示
步骤一
在根目录的api文件夹内建立一个pic.php文件,放入下面的代码:
<?phpdefined('IN_PHPCMS') or exit('No permission resources.'); if(isset($_SERVER['HTTP_REFERER'])){
if(strpos($_SERVER['HTTP_REFERER'],APP_PATH)==0){
pic();
}
else{
echo "Welcome to Picture Generation library system";
}}elseif(checkrobot()){
pic();}else{
echo "Welcome to Picture Generation library system";}function pic(){
$dst_path = IMG_PATH.'background/'.rand(1,20).'.jpg';//图片背景(背景图片名字格式为:.jpg,命名规则:数字.jpg,数字范围就是前面rand()函数里的数字范围)
$font = PC_PATH.'libs'.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'font'.DIRECTORY_SEPARATOR.'Alibaba-PuHuiTi-Bold.ttf';//这里的字体更换为自己想要的字体
$fontsize = 20;
$dst_nr = mb_substr(new_html_special_chars($_GET['txt']),0,10);//文字内容(默认截取10个汉字,靠左对齐)
$dst = imagecreatefromstring(file_get_contents($dst_path));//创建图片的实例
$color= imagecolorallocatealpha($dst,0,255,0,0);//配置颜色参数,透明度(前三个数字为颜色代码,最后一个是透明度)
$imgHeight = imagesy($dst);//生成图片高
$imgWidth = imagesx($dst);//生成图片宽
$fontWidth = imagefontwidth($fontsize);
$fontHeight = imagefontheight($fontsize);
$x = ($imgWidth-$fontWidth*strlen($dst_nr))/2;
$y = ($imgHeight-$fontHeight)/1.75;
imagefttext($dst, $fontsize, 0, $x, $y, $color, $font, $dst_nr);//生成文字(第一个参数为字体大小,0是倾斜度)
header('Content-Type: image/png');
imagejpeg($dst);
imagedestroy($dst);}//判断是不是蜘蛛function checkrobot($useragent=''){
static $kw_spiders = array('bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla');
static $kw_browsers = array('msie', 'netscape', 'opera', 'konqueror', 'mozilla');
$useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
if(strpos($useragent, 'http') === false && dstrpos($useragent, $kw_browsers)) return false;
if(dstrpos($useragent, $kw_spiders)) return true;
return false;}function dstrpos($string, $arr, $returnvalue = false) {
if(empty($string)) return false;
foreach((array)$arr as $v) {
if(strpos($string, $v) !== false) {
$return = $returnvalue ? $v : true;
return $return;
}
}
return false;}?>
步骤二
在statics/images目录里建立一个background文件夹,里面以数字形式放入jpg背景图片,如1.jpg,2.jpg,随机为20个,可增加更多,在20行的rand里扩大第二参数的20
保存自己需要的字体文件,放到/phpcms/libs/data/font文件夹内
步骤三
伪静态规则:
Apache伪静态:RewriteRule ^pic\/(.*?)\.jpg$ index.php?api.php?op=pic&txt=$1
Nginx伪静态:rewrite ^(.*)/pic/(.+).jpg$ $1/index.php?api.php?op=pic&txt=$2 last;
使用方法
以内容页为例
<img src="/pic/{$title}.jpg"/>
本文转载自周涛的个人博客。https://www.zhoutao.org/blog/2022/06/5764.html
发表评论 取消回复