public static function drawText($text, $ttfFont, $size, $textColor = 0xff, $backgroundColor = 0x0, $additionalConfigs = null) { $text = StringTools::toNumericEntities($text); $box = imagettfbbox($size, 0, $ttfFont, $text); $yOffset = $box[1]; $width = round($box[2] - $box[0] + $size * 0.2); $height = round($box[1] - $box[7] + $size * 0.2); $xOffset = $width > 50 ? 50 : round($width / 2); $image = imagecreate($width, $height); $cropCol = imagecolorallocate($image, 255, 0, 255); imagefilledrectangle($image, 0, 0, $width, $height, $cropCol); imagettftext($image, $size, 0, $xOffset, $height - $yOffset, imagecolorallocate($image, 255, 255, 255), $ttfFont, $text); $croppingPrecision = ArrayTools::get($additionalConfigs, 'croppingPrecision', 2); // Crop left $cropLeft = -1; for ($x = 0; $x < 50 + $width / 2; $x += $croppingPrecision) { if ($x >= $width) { $cropLeft = $x - 1; break; } for ($y = 0; $y < $height; $y += $croppingPrecision) { $col = imagecolorat($image, $x, $y); if ($col != 0) { $cropLeft = $x - 1; break 1; } } if ($cropLeft >= 0) { break; } } $xOffset = $xOffset - $cropLeft - 1; $yOffset = 0; $temp = imagettftext($image, $size, 0, 0, 0, $cropCol, $ttfFont, $text); if (ArrayTools::get($additionalConfigs, 'slim')) { $offset = $temp; } else { $offset = imagettftext($image, $size, 0, 0, 0, $cropCol, $ttfFont, 'BTj&#' . ord(utf8_decode('`')) . ';'); } $width = $temp[2] - $temp[0]; $height = abs($offset[5] - $offset[1]); if ($margin = ArrayTools::get($additionalConfigs, 'safeMargin')) { if (is_array($margin)) { $width += $margin[1] + $margin[3]; $xOffset += $margin[3]; $height += $margin[0] + $margin[2]; $yOffset += $margin[0]; } else { $width += $margin * 2; $height += $margin * 2; $xOffset += $margin; $yOffset += $margin; } } imagedestroy($image); $image = imagecreatetruecolor($width, $height); imagealphablending($image, false); imagesavealpha($image, true); $backgroundColor = self::colorHexToRgba($backgroundColor); $backgroundColor = imagecolorallocatealpha($image, $backgroundColor['r'], $backgroundColor['g'], $backgroundColor['b'], 127 - floor($backgroundColor['a'] / 2)); $textColor = self::colorHexToRgba($textColor); $textColor = imagecolorallocatealpha($image, $textColor['r'], $textColor['g'], $textColor['b'], 127 - floor($textColor['a'] / 2)); imagefilledrectangle($image, 0, 0, $width, $height, $backgroundColor); imagealphablending($image, true); imagettftext($image, $size, 0, $xOffset, -$offset[5] + $yOffset, $textColor, $ttfFont, $text); return $image; }