我正在尝试为我的欢迎页面创建图像,并希望将字符串以动态方式居中,否则使用诸如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);
解决方法:
尝试使用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);
标签:css,php
来源: https://codeday.me/bug/20191121/2054991.html