我正在尝试为我的欢迎页面创建一个图像,并希望将字符串动态居中,否则使用不同的用户名(例如 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);
Run Code Online (Sandbox Code Playgroud)
Tryimagefontwidth()函数获取每个字符的宽度并将其相乘,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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5713 次 |
| 最近记录: |