PHP文字转图片 PHP文字生成自适应图片Logo

该代码片段展示了如何使用PHP的GD库将文字转化为图片以及生成基于文字长度自适应的图片。主要函数imagettftext被用来在图像上添加文字,并调整图像尺寸以适应文本内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下是PHP文字转图片和PHP文字生成自适应图片的代码:

PHP文字转图片

// Create a 300x100 image
$image = imagecreatetruecolor(300, 100);

// Set the background color to white
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);

// Set the text color to black
$black = imagecolorallocate($image, 0, 0, 0);

// Add text to the image
$text = 'Hello world!';
imagettftext($image, 20, 0, 10, 50, $black, 'arial.ttf', $text);

// Save the image as JPEG
header('Content-Type: image/jpeg');
imagejpeg($image);

PHP文字生成自适应图片

 
//sample text
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam erat volutpat.";

//calculate image dimensions based on text length and font size
$font_size = 16;
$dimensions_array = imagettfbbox($font_size, 0, 'arial.ttf', $text);
$image_width = abs($dimensions_array[2] - $dimensions_array[0]) + 10;
$image_height = abs($dimensions_array[5] - $dimensions_array[3]) + 10;

//create image
$image = imagecreate($image_width, $image_height);

//set background to white
$bg_color = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $bg_color);

//set text color to black
$text_color = imagecolorallocate($image, 0, 0, 0);

//write text to image
imagettftext($image, $font_size, 0, 5, $dimensions_array[5], $text_color, 'arial.ttf', $text);

//output image as png
header('Content-Type: image/png');
imagepng($image);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值