I have created an image using the style of a div. The below shown is my div.
I am saving the style of the div in json format including background color, height, width, text, textcolor etc in database. The array looks like :
Array
(
[0] => stdClass Object
(
[itmTpe] => website
[width] => 110px
[height] => 25px
[left] => 350px
[top] => 122px
[zIndex] => 101
[dataB_URL] =>
[text] => Website
[iconDisp] => inline-block
[icon] => fa-globe
[font] => 22px
[color] => rgb(255, 255, 255)
[background] => rgb(7, 157, 236)
)
............
)
Using these details I am constructing an image. The code I have done is:
$json_code = json_decode(htmlspecialchars_decode($result['CP_Item'])); // returns array of div details
$i=1;
header('Content-Type: image/png');
foreach($json_code as $cp_item) // I have many such div elements with different styles
{
if($cp_item->itmTpe!='show_image' && $cp_item->itmTpe!='show_carousel' && $cp_item->itmTpe!='youtube_video')
{
if($cp_item->width)
$width= str_replace('px', '', $cp_item->width);
if($cp_item->height)
$height=str_replace('px', '', $cp_item->height);
$image = imagecreate($width, $height);
$background=$cp_item->background;
$bgcolor = str_replace(array('rgb(', ')', ' '), '', $background);
$arr = explode(',', $bgcolor);
$background = imagecolorallocate($image, $arr[0],$arr[1],$arr[2] );
$text=$cp_item->text;
if($cp_item->color)
$color=$cp_item->color;
$txtcolor = str_replace(array('rgb(', ')', ' '), '', $color);
$txtarr = explode(',', $txtcolor);
$textcolor=imagecolorallocate($image, $txtarr[0],$txtarr[1],$txtarr[2] );
$fontfile='fonts/times.ttf';
if($cp_item->font)
{
$size=str_replace('px', '', $cp_item->font);
}
else
{
$size=10;
}
// find the size of the image
$xi = ImageSX($image);
$yi = ImageSY($image);
// find the size of the text
$box = ImageTTFBBox($size, 0, $fontfile, $text);
$xr = abs(max($box[2], $box[4]));
$yr = abs(max($box[5], $box[7]));
// compute centering
$x = intval(($xi - $xr) / 2);
$y = intval(($yi + $yr) / 2);
//write the text at calculated position
imagettftext($image, $size, 0, $x+20, $y, $textcolor, $fontfile , $text);
$font2 = 'fonts/fontawesome-webfont.ttf';
$icontext=$icon[$cp_item->icon];
//places another text with smaller size
imagettftext($image, $size, 0, $x, $y, $textcolor, $font2, $icontext);
$file="createdimages/$pid/$i.png";
imagepng($image, $file);
$i++;
imagedestroy($image);
}
}
The image is getting created successfully. The problem is that the text in the image appears bigger than the font size used in div. I am using the font Times New Roman for both div text and image. But both shows differences. The resultant image is :
Also the size of the image looks smaller than the div size. I am constructing the image with the same width, height and font size of the div. I am not getting what is the problem with this?
I am new to GD. Can anyone help me to fix this? Thanks in advance.