使用php将imagestring()居中?

使用php将imagestring()居中?,php,css,Php,Css,我正在尝试为我的欢迎页面创建一个图像,并希望以友好的方式将字符串居中,否则使用不同的用户名就太糟糕了,比如:John和Alexandra header("Content-type: image/png"); $string1 = "Hello!"; $string2 = "Welcome to our website!"; $srting3 = "$username"; $font1 = 5; $font2 = 3; $font3 = 3; $img_w = 240; $img_h

我正在尝试为我的欢迎页面创建一个图像,并希望以友好的方式将字符串居中,否则使用不同的用户名就太糟糕了,比如:John和Alexandra

header("Content-type: image/png");

$string1 = "Hello!";
$string2 = "Welcome to our website!";
$srting3 = "$username";

$font1  = 5;
$font2  = 3;
$font3  = 3;

$img_w = 240;
$img_h =  64;

$image = imagecreatetruecolor ($img_w, $img_h);
$white = imagecolorallocate   ($image, 255,255,255);
$black = imagecolorallocate   ($image,   0,  0,  0);
imagefill($image, 0, 0, $white);

imagestring ($image, $font1, 110,  0, $string1, $black);
imagestring ($image, $font2,  60, 20, $string2, $black);
imagestring ($image, $font3, 105, 40, $string3, $black);

imagepng ($image);
imagedestroy($image);
试试这个:

<?php 
$im = imagecreate(150,50);
$text = 'bobcat';
$bgd = imagecolorallocate($im, 180,180,180);
$mid = imagecolorallocate($im, 160,160,160);

$fw = imagefontwidth(5);     // width of a character
$l = strlen($text);          // number of characters
$tw = $l * $fw;              // text width
$iw = imagesx($im);          // image width

$xpos = ($iw - $tw)/2;
$ypos = 20;

imagestring ($im, 5, $xpos, $ypos, $text, $mid);           // text in the middle

header("content-type: image/png");
imagepng($im);
imagedestroy($im);
?>

或者想想:

  • 创建背景图像

  • 创建带有文本的透明图像

  • 使用文本修剪透明图像并获取其尺寸

  • 做简单的数学txt_img.x=(bkg_img.width-txt_img.width)/2

  • 尝试使用
    imagefontwidth()
    函数获取每个字符的宽度,并将其与
    strlen($string)
    相乘。您还可以使用
    imagefontheight()
    更新高度

    header("Content-type: image/png");
    
    $string1 = "Hello!";
    $string2 = "Welcome to our website!";
    $srting3 = "$username";
    
    $font1  = 5;
    $width1 = imagefontwidth($font1) * strlen($string);
    $height1 = imagefontheight($font1);
    
    $font2  = 3;
    $width2 = imagefontwidth($font2) * strlen($string2);
    $height2 = imagefontheight($font2);
    
    $font3  = 3;
    $width3 = imagefontwidth($font3) * strlen($string3);
    $height3 = imagefontheight($font3);
    
    $img_w = 240;
    $img_h = 64;
    
    $image = imagecreatetruecolor ($img_w,$img_h);
    $white = imagecolorallocate ($image,255,255,255);
    $black = imagecolorallocate ($image,0,0,0);
    imagefill($image,0,0,$white);
    
    imagestring ($image,$font1,($img_w/2)-($width1/2),        0,$string1,$black);
    imagestring ($image,$font2,($img_w/2)-($width2/2), $height1,$string2,$black);
    imagestring ($image,$font3,($img_w/2)-($width3/2), $height1+$height2,$string3,$black);
    
    
    imagepng ($image);
    imagedestroy($image);