$draw = new \ImagickDraw();
$imagick = new \Imagick();
$imagick->newImage($width, $height, new \ImagickPixel('none'));
$draw->setFillColor($color);
$draw->setFont($font_file);
$draw->setFontSize($size);
$draw->setTextEncoding('UTF-8');
$stringArr = $this->mbStringToArray($text);
$textHeight = 0;
$textWidth = 0;
$charCount = count($stringArr);
$texts = [];
foreach ($stringArr as $char) {
$metrics = $imagick->queryFontMetrics($draw, $char, true);
$charHeight = $metrics['textHeight'];
$charWidth = $metrics['textWidth'];
$textHeight += $charHeight;
$textWidth += $charWidth;
$texts[] = ['char' => $char, 'height' => $charHeight, 'width' => $charWidth];
}
if ($direction == 2) {
if ($charCount > 1) {
$textHeight += ($charCount - 1) * $space;
}
$draw->setTextAlignment(\Imagick::ALIGN_CENTER);
$x = $size / 2;
if ($textHeight > $height) {
$offset = 0;
} else {
$offset = ($height - $textHeight) / 2;
}
$y = $offset;
foreach ($texts as $c) {
$y += $c['height'];
$draw->annotation($x, $y, $c['char']);
$y += $space;
}
} else {
if ($charCount > 1) {
$textWidth += ($charCount - 1) * $space;
}
$metrics = $imagick->queryFontMetrics($draw, $text, false);
$y = $metrics['ascender'];
$draw->setTextAlignment(\Imagick::ALIGN_LEFT);
if ($align == \Imagick::ALIGN_CENTER) {
if ($textWidth > $width) {
$x = 0;
} else {
$x = ($width - $textWidth) / 2;
}
} elseif ($align == \Imagick::ALIGN_RIGHT) {
$x = $width - $textWidth;
} else {
$x = 0;
}
foreach ($texts as $c) {
$draw->annotation($x, $y, $c['char']);
$x += $c['width'] + $space;
}
}
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();