<?php
class WriteTextToImage
{
public $textOrientation = 'vertical';
public $font = 'arial.ttf';
public $image = 'blank.jpg';
public $linePaddingBottom = 10;
public $linePaddingRight = 5;
public $text;
public function __construct($text)
{
$this->text = $text;
}
public function getImage()
{
header('Content-type: image/jpeg');
$image = imagecreatefromjpeg($this->image);
$lines = $this->getLinesAndColorByText();
$positionY = 15;
$positionX = 0;
$count = count($lines);
$i = 0;
foreach ($lines as $line) {
if(++$i === $count) {
$this->linePaddingRight -= 5;
}
$position = imagettfbbox(10, 0, $this->font, $line['text']);
$positionY += abs($position[7]) - abs($position[1]) + $this->linePaddingBottom;
$positionX += abs($position[2] - $position[0]) + $this->linePaddingRight;
$color = imagecolorallocate($image, $line['color']['r'], $line['color']['g'], $line['color']['b']);
if ($this->textOrientation == 'vertical') {
imagettftext($image, 10, 0, $positionX, 30, $color, $this->font, $line['text']);
} else {
imagettftext($image, 10, 0, 10, $positionY, $color, $this->font, $line['text']);
}
}
imagejpeg($image);
imagedestroy($image);
}
public function getLinesAndColorByText()
{
$result = [];
$lines = explode('§', $this->text);
$lines = array_filter($lines);
foreach ($lines as $index => $line) {
$result[$index]['color'] = $this->getColorByCode($line[0]);
$result[$index]['text'] = substr(trim($line), 1);
}
return $result;
}
public function getColorByCode($code)
{
$rgbColors = [];
switch ($code) {
case 'f':
$rgbColors['r'] = 0;
$rgbColors['g'] = 0;
$rgbColors['b'] = 0;
break;
case 0:
$rgbColors['r'] = 0;
$rgbColors['g'] = 0;
$rgbColors['b'] = 0;
break;
case 4:
$rgbColors['r'] = 192;
$rgbColors['g'] = 57;
$rgbColors['b'] = 43;
break;
default:
$rgbColors['r'] = 0;
$rgbColors['g'] = 0;
$rgbColors['b'] = 0;
break;
}
return $rgbColors;
}
}
$image = new WriteTextToImage('§fValami §0szöveg §4féleség §4kukiság');
$image->getImage();
?>