近期开发项目时,需要将网页中的统计报表生成为图片,并发送到钉钉群消息内。开发完成后如下总结。
下图是生成的伪效果图。
生成表格图片,主要分为 画图、画表格和填充数据等。
画图:
$image = imagecreatetruecolor(图片宽度, 图片高度);
画表格:
imageline($image, x坐标1, y坐标1, x坐标2, y坐标2, 颜色);
填充数据:
imagettftext($image, 字体大小, 0,左偏移, 高度, 字体颜色, 字体, 数据);
额外:
文字加粗,可以多次执行 imagettftext 函数,比如执行3遍,即可实现加粗的效果
线条加粗,可用如下伪代码实现。
- /**
- * 绘制粗线
- */
- public function imageLineThick($image, $x1, $y1, $x2, $y2, $color, $thick = 1)
- {
- if ($thick == 1) {
- return imageline($image, $x1, $y1, $x2, $y2, $color);
- }
- $t = $thick / 2 - 0.5;
- if ($x1 == $x2 || $y1 == $y2) {
- return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);
- }
- $k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q
- $a = $t / sqrt(1 + pow($k, 2));
- $points = array(
- round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),
- round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),
- round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),
- round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),
- );
- imagefilledpolygon($image, $points, 4, $color);
- return imagepolygon($image, $points, 4, $color);
- }
最后附上源代码,有需要的朋友可以直接拉取使用。GitHub - revert-yang/GDTableContribute to revert-yang/GDTable development by creating an account on GitHub.https://github.com/revert-yang/GDTable