在 php 中将文本转换为图像解决方案 1(自动调整大小的输出):解决方案 2(手动大小的输出):
2022-08-30 19:03:24
我想设置从表单字段获取的文本字符串的样式,然后将其转换为透明.PNG(alpha BG)。
这在 PHP 中是可能的吗?如果是这样,请您向我展示如何实现这一目标
我想设置从表单字段获取的文本字符串的样式,然后将其转换为透明.PNG(alpha BG)。
这在 PHP 中是可能的吗?如果是这样,请您向我展示如何实现这一目标
是的,这很有可能,您将在生成验证码图像时遵循与我们相同的技术。
要求:GD库应该在你的php中启用。
代码(取自 php 帮助文件 ;)
<?php
// Set the content-type
header('Content-type: image/png');
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';
// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
将文本转换为图像(php 代码):
首先,您需要确保托管已启用GD库(在新的php文件中,执行并在输出中查看/查找GD库是否已启用)。phpinfo();
TextToImage_my( $text='Helloooo! my unicode words: ǩ Ƥ Ў ض ط Ⴓ ');
// ==== other parameters can be used too, see the function arguments below
函数代码:文本到图像.php
(需要手动输出宽度和高度,剪掉更长的字符串)。
<?php
$text = "YOUR texttttttttttttttt";
$my_img = imagecreate( 200, 80 ); //width & height
$background = imagecolorallocate( $my_img, 0, 0, 255 );
$text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
$line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
imagestring( $my_img, 4, 30, 25, $text, $text_colour );
imagesetthickness ( $my_img, 5 );
imageline( $my_img, 30, 45, 165, 45, $line_colour );
header( "Content-type: image/png" );
imagepng( $my_img );
imagecolordeallocate( $line_color );
imagecolordeallocate( $text_color );
imagecolordeallocate( $background );
imagedestroy( $my_img );
?>