文字转图片应用小记(php版)

2019-07-04 | 2,794浏览 | 0评论 | 标签:无

txt2img.jpg

应用场景

文字转图片的应用场景非常之多,比如文章防爬、躲避GFW敏感词审查等。

比如下边这张文章截图,里面有些词语就被换成了图片,能看出来吗?

txt2img-demo.jpg

效果演示

[demo地址]

实现代码

// (代码从网上整理而来)
// 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=哈哈哈哈" />

后话

文字的样式(字号、字体、文字色、背景色、间距、方向等)都可以自定义,稍加优化就能达到以假乱真的效果。

(本篇完。有疑问欢迎留言探讨)

留言:

*

* (方便回复通知)

打赏
编辑代码 运行结果
退出