我使用div的样式创建了一个图像。下面显示的是我的div。
我将以json格式保存div的样式,包括数据库中的背景颜色,高度,宽度,文本,文本颜色等。该数组看起来像:
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)
)
............
)
使用这些细节我正在构建一个图像。我所做的代码是:
$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);
}
}
图像已成功创建。问题是图像中的文本看起来比div中使用的字体大。我正在使用字体Times New Roman来处理div文本和图像。但两者都显示出差异。结果图像是:
此外,图像的大小看起来小于div大小。我正在构建具有相同宽度,高度和div字体大小的图像。我不知道这有什么问题?
我是GD新手。任何人都可以帮我解决这个问题吗?提前谢谢。
答案 0 :(得分:1)
字体应该有一个单位而不是像素。实际上,GD按预期输出图像(110x25),而你的div可能有一个内部填充,增加了图像尺寸。