• 注册
  • 程序猿 程序猿 关注:0 内容:12

    PHP实现占位图片功能

  • 查看作者
  • 打赏作者
    • 使用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');}

      请登录之后再进行评论

      登录
    • 到底部
    • 做任务
    • 实时动态
    • 换皮肤
    • 帖子间隔 侧栏位置:
      版权所有©(2022)ShenLin.ink All Rights Reserved. 粤ICP备2022103881号