前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PHP实现占位图片功能

PHP实现占位图片功能

作者头像
申霖
发布2020-11-19 14:10:10
9420
发布2020-11-19 14:10:10
举报
文章被收录于专栏:小白程序猿小白程序猿

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

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

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

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

话不多少,先上代码

代码语言:javascript
复制
/**
 * 生成占位图片
 * @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');
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-11-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档