使用透明度在PHP中创建圆形png图像,并在其中居中显示一个字母


Create round png image in PHP using transparency and center a letter in it

我想为我的网站创建个人资料图片。图像应该是圆形的,纯色的背景色和正好在中心的单个大字母。

到目前为止,我已经能够创建一个方形的 png 图像和其中的字母,但它没有居中。由于不同的字母具有不同的宽度,我得到一些字母略微偏离中心。

我将使用透明度在PHP中实现"圆形"png图像。

这是完整的脚本,应该开箱即用。如果你想使用自定义字体,你需要Arial.tff,但这不是严格需要的。

有一个带有一些颜色的查找表。单个字母被散列(是的,我知道很愚蠢,但这样它更灵活,因为我可以传递我喜欢的任何字符串)并选择颜色。

<?php
$text = "a";
$posx = 40;
$posy = 150;
$size = 120;
$displaytext = strtoupper($text);
$image = imagecreatetruecolor(200, 200);
// pick a background at random
$binhash = md5($text, true);
$numhash = unpack('N2', $binhash);
$index = abs($numhash[1]) % 16;
$palette = array(
array(0xde,0x5a,0xa4),
array(0xae,0xc6,0xcf),
array(0x96,0x6f,0xd6),
array(0xff,0xb3,0x47),
array(0xff,0x69,0x61),
array(0x77,0xdd,0x77),
array(0x03,0xc0,0x3c),
array(0xcf,0xcf,0xc4),
array(0xc2,0x3b,0x22),
array(0xfd,0xfd,0x96),
array(0x83,0x69,0x53),
array(0x77,0x9e,0xcb),
array(0xb1,0x9c,0xd9),
array(0xb3,0x9e,0xb5),
array(0xf4,0x9a,0xc2),
array(0xff,0xd1,0xdc)
);
$r = $palette[$index][0];
$g = $palette[$index][1];
$b = $palette[$index][2];
$image = imageCreate(200, 200);
imageColorAllocate($image, $r, $g, $b);
$color = imageColorAllocate($image, 255, 255, 255);
$font = 'arial.ttf';

$box = imagettfbbox(200, 0, "ARIAL", $displaytext);
$width = abs($box[2] - $box[0]);
$height = abs($box[5] - $box[1]);
$image = imageCreate(200, 200);
imageColorAllocate($image, $r, $g, $b);
$color = imageColorAllocate($image, 255, 255, 255);
$font = 'arial.ttf';
imagettftext($image, 200, 0, 0 + (200/2 - floor($width/2)), 200, $color, "ARIAL", $displaytext);
header("content-type: image/png");
imagepng($image);
imagedestroy($image);
?>

我怎样才能修改这样的代码,以便:

  • 有圆角。我应该在中心创建一个透明背景和一个实心圆盘吗?
  • 让字母居中,无论它是哪个字母

可以帮助您使字母居中

<?php
$im = new Imagick(); /* Create a new Imagick object */
$draw = new ImagickDraw(); /* Create an ImagickDraw object */
$draw->setFont('/path/to/font.ttf'); /* Set the font */
var_dump($im->queryFontMetrics($draw, "K")); /* Dump the font metrics*/
?>

使用字体度量,您可以计算具有特定字体的特定字母/文本的宽度和高度,并且可以访问属性。 希望对您有所帮助。