PHP实现占位图片功能

发布时间:2020-11-17 21:56:03 浏览量:835 标签: 占位图片

使用PHP来实现占位图片功能,本次开发以thinkphp框架为例,以下为注意事项:

1、生成图片最大宽度为2048px;

2、未设置文本内容,默认使用的是宽 * 高形式;

3、引入字体为本地字体文件,路径为绝对地址;



话不多少,先上代码

/**
 * 生成占位图片
 * @return \think\Response
 */
public function data()
{
    // 图片宽度
    $width = input('get.width') > 2048 ? 2048 : input('get.width');
    // 图片高度
    $height = input('get.height');
    // 文本大小
    $size = $height * 0.1;
    // 设置文本内容
    $content = $width . ' x ' . $height;
    // 创建画布
    $im = imagecreatetruecolor($width, $height);
    // 设置文本颜色
    $textColor = imagecolorallocate($im, 158, 158, 158);
    // 设置画布颜色
    $backgroundColor = imagecolorallocate($im, 97, 97, 97);
    // 创建画布并且填充颜色
    imagefilledrectangle($im, 0, 0, $width, $height, $textColor);
    // 设置字体文字路径
    $fontPath = realpath('./msyh.ttf');
    //计算文本范围
    $position = imagettfbbox($size, 0, $fontPath, $content);
    $x        = ($width - $position[2] - $position[0]) / 2;
    $y        = ($height - $position[3] - $position[5]) / 2;
    // 写入文本
    imagefttext($im, $size, 0, $x, $y, $backgroundColor, $fontPath, $content);
    // 开启缓存
    ob_start();
    // 输出图像
    imagepng($im);
    // 获取并清除缓存
    $content = ob_get_clean();
    imagedestroy($im);
    // 输出图像
    return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/png');
}



评论
登录后才可以进行评论哦! QQ登录
验证码
评论内容