用php中心imagestring()?

时间:2014-04-13 12:26:49

标签: php css

我正在尝试为我的欢迎页面创建一个图像,并希望将这些字符串置于dinamically中心,否则它会因为不同的用户名而过于糟糕: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);

2 个答案:

答案 0 :(得分:3)

尝试使用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);

答案 1 :(得分:0)

试试这个:

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

或者想一想:

  1. 创建背景图片

  2. 使用文字

  3. 创建透明图像
  4. 使用文本修剪透明图像并获取其尺寸

  5. 做简单的数学运算txt_img.x =(bkg_img.width-txt_img.width)/ 2;