在PHP中将文本转换为图像

22

我想要对从表单字段获取的文本字符串进行样式设置,并将其转换为透明的 .PNG(带有 alpha 背景)。

使用 PHP 可以实现吗?如果可以,请您向我展示如何完成此操作。


您可以尝试这个网站:http://www.daftlogic.com/projects-text-to-image.htm - Hoàng Vũ Tgtt
3个回答

29

是的,这是完全可能的。你需要按照生成验证码图片的方法来做。

要求:你的 PHP 必须启用 GD 库。

代码(来自 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);
?> 

18

将文本转换为图片 (php 代码):

首先,您需要确保托管服务已启用GD库(在新的php文件中,执行phpinfo();并在输出中查找GD库是否已启用)。

解决方案1(自动调整大小的输出):

TextToImage_my( $text='Helloooo! my unicode words:  ǩ Ƥ Ў  ض ط  Ⴓ ');
    // ==== other parameters can be used too, see the function arguments below

函数代码:text-to-image.php


解决方案2(手动设置输出大小):

(需要手动设置输出的宽度和高度,较长的字符串会被裁剪)。

<?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 );
?> 

2
感谢您提供的自适应解决方案 :) - Alain Tiemblo
一个问题...在输入文本中是否可以换行? - Julyano Felipe
1
解决方案1非常出色! - JohnA10
https://www.php.net/manual/zh/function.imagecolordeallocate.php 需要两个参数,imagecolordeallocate(GdImage $image, int $color) - Avatar

0
$image = imagecreate(widthyouwant,heightyouwant);
$bg = imagecolorallocatealpha($image,255,255,255,0);
$black = imagecolorallocate($image,255,255,255);
imagettftext($image,fontsize, 0, x, y, $black, "fontlocation", $_GET['text']);
header('Content-Type: image/png');
imagepng($image);

你可以通过以下方式显示图像:

我认为这是正确的,因为我已经有一段时间没有做过这个了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接