GD 安装、配置
考虑到功能需要使用字体库、图像格式 jpeg\png 所以先安装相关库。
字体库 FreeType 2
# 在临时目录进行操作
cd /tmp
# https://download.savannah.gnu.org/releases/freetype/
wget http://download.savannah.gnu.org/releases/freetype/freetype-2.10.1.tar.gz
tar zxvf freetype-2.10.1.tar.gz
cd freetype-2.10.1
./configure --prefix=/usr/local/freetype && make && make install
图像格式 jpeg
cd /tmp
# http://www.ijg.org/
wget http://www.ijg.org/files/jpegsrc.v9d.tar.gz
tar zxvf jpegsrc.v9.tar.gz
cd jpeg-9/
./configure --prefix=/usr/local/jpeg && make && make install
图像格式 png
cd /tmp
# http://www.libpng.org/pub/png/libpng.html
wget https://download.sourceforge.net/libpng/libpng-1.6.37.tar.gz --no-check-certificate
tar zxvf libpng-1.6.37.tar.gz
cd libpng-1.6.37
./configure --prefix=/usr/local/libpng && make && make install
安装 GD
背景:服务器 php 7.1 通过编译自行安装的。
# 到 php 源码 dir
cd {php-source-dir}/ext/gd/
# 生成 configure 文件
{php-dir}/bin/phpize
# 查看可用参数
./configure --help
# 设置参数
./configure --with-php-config={php-dir}/bin/php-config --with-jpeg-dir=/usr/local/jpeg --with-png-dir=/usr/local/libpng --with-freetype-dir=/usr/local/freetype --enable-gd-native-ttf
make && make install
vim {php-dir}/lib/php.ini
# 最底下增加一行
extension=gd.so
service php-fpm reload
# 检查
php -r "var_dump(gd_info());"
编译前一定要记得 make clean
清除上次的编译内容,尤其是已经编译安装过的。
实例
$pic = imagecreate($maxWidth, $maxHeight);
//定义颜色
$black = imagecolorallocate($pic, 0, 0, 0);
$white = imagecolorallocate($pic, 255, 255, 255);
// 白底
imagefill($pic, 0, 0, $white);
// 打水印
imagettftext($pic, $fontSize, 30, $x, $y, $lightGrey, $fontFile, $mark);
imagejpeg($pic, $resultPath, 100);
imagedestroy($pic);
文字右对齐:
// https://php.golaravel.com/function.imagettfbbox.html
$bbox = imagettfbbox($fontSize, 0, $fontFile, $text);
$offset = $colWidth - $bbox[2] - 50;
imagettftext($pic, $fontSize, 0, $x + $offset, $y, $_color, $fontFile, $text);
遇到的报错
Call to undefined function imagettftext()
出现此问题应该就是 FreeType
没有装好,可参考上面的步骤。
References
– EOF –