在php中将文本转换为图像

时间:2010-12-20 10:00:36

标签: php

我想设置从表单字段中取出的文本字符串,然后将其转换为透明的.PNG(alpha BG)。

PHP可以实现吗?如果是这样,你能否告诉我如何实现这一目标

4 个答案:

答案 0 :(得分:25)

是的,它非常可能,您将在生成验证码图像时遵循与我们相同的技术。

要求:应在您的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);
?> 

答案 1 :(得分:16)

将文字转换为图片(php code):

首先,您需要确保托管已启用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 :(得分:0)

我认为您可以使用PHP GD库实现此目的:http://php.net/manual/en/ref.image.php

答案 3 :(得分: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);

然后你可以通过去显示图像 我认为这是正确的,因为我已经做了一段时间。