
文字转图片应用小记(php版)
2019-07-04 | 1,036浏览 | 0评论 | 标签:无
应用场景
文字转图片的应用场景非常之多,比如文章防爬、躲避GFW敏感词审查等。
比如下边这张文章截图,里面有些词语就被换成了图片,能看出来吗?
效果演示
实现代码
// (代码从网上整理而来)
// index.php
<?php
$text_string = $_REQUEST["t"];
$font_ttf = "simhei.ttf";
$font_size = 14;
$text_angle = 0;
$text_padding = 0;
$the_box = calculateTextBox($text_string, $font_ttf, $font_size, $text_angle);
$imgWidth = $the_box["width"] + $text_padding;
$imgHeight = $the_box["height"] + $text_padding;
$image = imagecreate($imgWidth,$imgHeight);
imagecolorallocatealpha($image,255,255,255,127);
$color = imagecolorallocate($image,0,0,0);
imagettftext($image,
$font_size,
$text_angle,
$the_box["left"] + ($imgWidth / 2) - ($the_box["width"] / 2),
$the_box["top"] + ($imgHeight / 2) - ($the_box["height"] / 2),
$color,
$font_ttf,
$text_string);
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
$rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);
$minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
$maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
$minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
$maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));
return array(
"left" => abs($minX) - 1,
"top" => abs($minY) - 1,
"width" => $maxX - $minX,
"height" => $maxY - $minY,
"box" => $rect
);
}
?>
//调用
<img src="/index.php?t=哈哈哈哈" />
后话
文字的样式(字号、字体、文字色、背景色、间距、方向等)都可以自定义,稍加优化就能达到以假乱真的效果。
(本篇完。有疑问欢迎留言探讨, 也可以交个金钱朋友Buy me a coffee)
热门文章
- 微信小程序“拍照识图”上线(46,121)
- vue+tabs动态组件方案漫谈(13,342)
- 基金助手--chrome浏览器插件(13,049)
- 网页打印插件Print.js(11,891)
- px转rem/vw方法小结(7,898)
- 简易的上下循环滚动代码(7,291)
- qq表情在线制作器(7,174)
- 侧边滑出弹层插件mSlider.js(5,556)
- Vue模拟select多选(5,220)
- 前端项目集成工具 ProjectHub(4,944)