以下是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);