当前位置: 首页 > 编程文章 >

PHP带Logo二维码生成类详解

PHP带Logo二维码生成类详解

作者:苏知时间:2026-03-03 13:49:34浏览:600

本文介绍一个基于PHP实现的二维码生成类,支持在二维码中嵌入Logo并自定义尺寸、描边、圆角及透明度等属性。该类提供完整的代码实现、演示实例及详细的参数配置说明,方便开发者快速集成到项目中。

本文目录展开

PHP带Logo二维码生成类功能概述

本示例详细解析了利用PHP编写的带有Logo图标的二维码生成类库。以下内容供广大开发者参考学习。

该方案提供了一个功能完善的PHP二维码生成类,具备调整二维码尺寸、嵌入Logo图像、添加描边效果、设置圆角以及控制透明度等多种处理能力。文中附带完整源代码、运行演示案例以及详尽的参数解读,旨在协助用户高效掌握并使用该工具。

该类主要实现了以下核心功能:

1. 生成标准二维码 2. 将Logo图标叠加至二维码中心 3. 支持为Logo添加描边效果 4. 支持对Logo进行圆角处理 5. 可调节Logo的不透明度 6. Logo源文件及最终输出格式均支持PNG、JPG和GIF 7. 允许自定义输出图片的质量参数

以下是各类参数的具体设定说明:

ecc 二维码质量 L-smallest, M, Q, H-best
size 二维码尺寸 1-50
dest_file 生成的二维码图片路径
quality 生成的图片质量
logo logo路径,为空表示不加入logo
logo_size logo尺寸,null表示按二维码尺寸比例自动计算
logo_outline_size logo描边尺寸,null表示按logo尺寸按比例自动计算
logo_outline_color logo描边颜色
logo_opacity logo不透明度 0-100
logo_radius logo圆角角度 0-30

核心代码实现如下:

PHPQRCode.class.php


<?php
require_once dirname(__FILE__)."/qrcode/qrlib.php";
/**
 * PHP创建二维码类
 * Date:  2018-03-18
 * Author: fdipzone
 * Version: 1.0
 *
 * Description:
 * PHP实现创建二维码类,支持设置尺寸,加入LOGO,圆角,透明度,等处理。
 *
 * Func:
 * public set_config      设定配置
 * public generate       创建二维码
 * private create_qrcode    创建纯二维码图片
 * private add_logo       合拼纯二维码图片与logo图片
 * private image_outline    图片对象进行描边
 * private image_fillet     图片对象进行圆角处理
 * private imagecopymerge_alpha 合拼图片并保留各自透明度
 * private create_dirs     创建目录
 * private hex2rgb       hex颜色转rgb颜色
 * private get_file_ext     获取图片类型
 */
class PHPQRCode{ // class start
  /** 默认设定 */
  private $_config = array(
    'ecc' => 'H',            // 二维码质量 L-smallest, M, Q, H-best
    'size' => 15,            // 二维码尺寸 1-50
    'dest_file' => 'qrcode.png',    // 创建的二维码路径
    'quality' => 100,          // 图片质量
    'logo' => '',            // logo路径,为空表示没有logo
    'logo_size' => null,        // logo尺寸,null表示按二维码尺寸比例自动计算
    'logo_outline_size' => null,    // logo描边尺寸,null表示按logo尺寸按比例自动计算
    'logo_outline_color' => '#FFFFFF', // logo描边颜色
    'logo_opacity' => 100,       // logo不透明度 0-100
    'logo_radius' => 0,         // logo圆角角度 0-30
  );
  /**
   * 设定配置
   * @param Array  $config 配置内容
   */
  public function set_config($config){
    // 允许设定的配置
    $config_keys = array_keys($this->_config);
    // 获取传入的配置,写入设定
    foreach($config_keys as $k=>$v){
      if(isset($config[$v])){
        $this->_config[$v] = $config[$v];
      }
    }
  }
  /**
   * 创建二维码
   * @param String $data 二维码内容
   * @return String
   */
  public function generate($data){
    // 创建临时二维码图片
    $tmp_qrcode_file = $this->create_qrcode($data);
    // 合拼临时二维码图片与logo图片
    $this->add_logo($tmp_qrcode_file);
    // 删除临时二维码图片
    if($tmp_qrcode_file!='' && file_exists($tmp_qrcode_file)){
      unlink($tmp_qrcode_file);
    }
    return file_exists($this->_config['dest_file'])? $this->_config['dest_file'] : '';
  }
  /**
   * 创建临时二维码图片
   * @param String $data 二维码内容
   * @return String
   */
  private function create_qrcode($data){
    // 临时二维码图片
    $tmp_qrcode_file = dirname(__FILE__).'/tmp_qrcode_'.time().mt_rand(100,999).'.png';
    // 创建临时二维码
    QRcode::png($data, $tmp_qrcode_file, $this->_config['ecc'], $this->_config['size'], 2);
    // 返回临时二维码路径
    return file_exists($tmp_qrcode_file)? $tmp_qrcode_file : '';
  }
  /**
   * 合拼临时二维码图片与logo图片
   * @param String $tmp_qrcode_file 临时二维码图片
   */
  private function add_logo($tmp_qrcode_file){
    // 创建目标文件夹
    $this->create_dirs(dirname($this->_config['dest_file']));
    // 获取目标图片的类型
    $dest_ext = $this->get_file_ext($this->_config['dest_file']);
    // 需要加入logo
    if(file_exists($this->_config['logo'])){
      // 创建临时二维码图片对象
      $tmp_qrcode_img = imagecreatefrompng($tmp_qrcode_file);
      // 获取临时二维码图片尺寸
      list($qrcode_w, $qrcode_h, $qrcode_type) = getimagesize($tmp_qrcode_file);
      // 获取logo图片尺寸及类型
      list($logo_w, $logo_h, $logo_type) = getimagesize($this->_config['logo']);
      // 创建logo图片对象
      switch($logo_type){ 
        case 1: $logo_img = imagecreatefromgif($this->_config['logo']); break; 
        case 2: $logo_img = imagecreatefromjpeg($this->_config['logo']); break; 
        case 3: $logo_img = imagecreatefrompng($this->_config['logo']); break; 
        default: return ''; 
      }
      // 设定logo图片合拼尺寸,没有设定则按比例自动计算
      $new_logo_w = isset($this->_config['logo_size'])? $this->_config['logo_size'] : (int)($qrcode_w/5);
      $new_logo_h = isset($this->_config['logo_size'])? $this->_config['logo_size'] : (int)($qrcode_h/5);
      // 按设定尺寸调整logo图片
      $new_logo_img = imagecreatetruecolor($new_logo_w, $new_logo_h);
      imagecopyresampled($new_logo_img, $logo_img, 0, 0, 0, 0, $new_logo_w, $new_logo_h, $logo_w, $logo_h);
      // 判断是否需要描边
      if(!isset($this->_config['logo_outline_size']) || $this->_config['logo_outline_size']>0){
        list($new_logo_img, $new_logo_w, $new_logo_h) = $this->image_outline($new_logo_img);
      }
      // 判断是否需要圆角处理
      if($this->_config['logo_radius']>0){
        $new_logo_img = $this->image_fillet($new_logo_img);
      }
      // 合拼logo与临时二维码
      $pos_x = ($qrcode_w-$new_logo_w)/2;
      $pos_y = ($qrcode_h-$new_logo_h)/2;
      imagealphablending($tmp_qrcode_img, true);
      // 合拼图片并保留各自透明度
      $dest_img = $this->imagecopymerge_alpha($tmp_qrcode_img, $new_logo_img, $pos_x, $pos_y, 0, 0, $new_logo_w, $new_logo_h, $this->_config['logo_opacity']);
      // 生成图片
      switch($dest_ext){
        case 1: imagegif($dest_img, $this->_config['dest_file'], $this->_config['quality']); break;
        case 2: imagejpeg($dest_img, $this->_config['dest_file'], $this->_config['quality']); break;
        case 3: imagepng($dest_img, $this->_config['dest_file'], (int)(($this->_config['quality']-1)/10)); break;
      } 
    // 不需要加入logo
    }else{
      $dest_img = imagecreatefrompng($tmp_qrcode_file);
      // 生成图片
      switch($dest_ext){
        case 1: imagegif($dest_img, $this->_config['dest_file'], $this->_config['quality']); break;
        case 2: imagejpeg($dest_img, $this->_config['dest_file'], $this->_config['quality']); break;
        case 3: imagepng($dest_img, $this->_config['dest_file'], (int)(($this->_config['quality']-1)/10)); break;
      }
    }
  }
  /**
   * 对图片对象进行描边
   * @param Obj  $img 图片对象
   * @return Array
   */
  private function image_outline($img){
    // 获取图片宽高
    $img_w = imagesx($img);
    $img_h = imagesy($img);
    // 计算描边尺寸,没有设定则按比例自动计算
    $bg_w = isset($this->_config['logo_outline_size'])? intval($img_w + $this->_config['logo_outline_size']) : $img_w + (int)($img_w/5);
    $bg_h = isset($this->_config['logo_outline_size'])? intval($img_h + $this->_config['logo_outline_size']) : $img_h + (int)($img_h/5);
    // 创建底图对象
    $bg_img = imagecreatetruecolor($bg_w, $bg_h);
    // 设置底图颜色
    $rgb = $this->hex2rgb($this->_config['logo_outline_color']);
    $bgcolor = imagecolorallocate($bg_img, $rgb['r'], $rgb['g'], $rgb['b']);
    // 填充底图颜色
    imagefill($bg_img, 0, 0, $bgcolor);
    // 合拼图片与底图,实现描边效果
    imagecopy($bg_img, $img, (int)(($bg_w-$img_w)/2), (int)(($bg_h-$img_h)/2), 0, 0, $img_w, $img_h);
    $img = $bg_img;
    return array($img, $bg_w, $bg_h);
  }
  /**
   * 对图片对象进行圆角处理
   * @param Obj $img 图片对象
   * @return Obj
   */
  private function image_fillet($img){
    // 获取图片宽高
    $img_w = imagesx($img);
    $img_h = imagesy($img);
    // 创建圆角图片对象
    $new_img = imagecreatetruecolor($img_w, $img_h);
    // 保存透明通道
    imagesavealpha($new_img, true);
    // 填充圆角图片
    $bg = imagecolorallocatealpha($new_img, 255, 255, 255, 127);
    imagefill($new_img, 0, 0, $bg);
    // 圆角半径
    $r = $this->_config['logo_radius'];
    // 执行圆角处理
    for($x=0; $x<$img_w; $x++){
      for($y=0; $y<$img_h; $y++){
        $rgb = imagecolorat($img, $x, $y);
        // 不在图片四角范围,直接画图
        if(($x>=$r && $x<=($img_w-$r)) || ($y>=$r && $y<=($img_h-$r))){
          imagesetpixel($new_img, $x, $y, $rgb);
        // 在图片四角范围,选择画图
        }else{
          // 上左
          $ox = $r; // 圆心x坐标
          $oy = $r; // 圆心y坐标
          if( ( ($x-$ox)*($x-$ox) + ($y-$oy)*($y-$oy) ) <= ($r*$r) ){
            imagesetpixel($new_img, $x, $y, $rgb);
          }
          // 上右
          $ox = $img_w-$r; // 圆心x坐标
          $oy = $r;    // 圆心y坐标
          if( ( ($x-$ox)*($x-$ox) + ($y-$oy)*($y-$oy) ) <= ($r*$r) ){
            imagesetpixel($new_img, $x, $y, $rgb);
          }
          // 下左
          $ox = $r;    // 圆心x坐标
          $oy = $img_h-$r; // 圆心y坐标
          if( ( ($x-$ox)*($x-$ox) + ($y-$oy)*($y-$oy) ) <= ($r*$r) ){
            imagesetpixel($new_img, $x, $y, $rgb);
          }
          // 下右
          $ox = $img_w-$r; // 圆心x坐标
          $oy = $img_h-$r; // 圆心y坐标
          if( ( ($x-$ox)*($x-$ox) + ($y-$oy)*($y-$oy) ) <= ($r*$r) ){
            imagesetpixel($new_img, $x, $y, $rgb);
          }
        }
      }
    }
    return $new_img;
  }
  // 合拼图片并保留各自透明度
  private function imagecopymerge_alpha($dest_img, $src_img, $pos_x, $pos_y, $src_x, $src_y, $src_w, $src_h, $opacity){
    $w = imagesx($src_img);
    $h = imagesy($src_img);
    $tmp_img = imagecreatetruecolor($src_w, $src_h);
    imagecopy($tmp_img, $dest_img, 0, 0, $pos_x, $pos_y, $src_w, $src_h);
    imagecopy($tmp_img, $src_img, 0, 0, $src_x, $src_y, $src_w, $src_h);
    imagecopymerge($dest_img, $tmp_img, $pos_x, $pos_y, $src_x, $src_y, $src_w, $src_h, $opacity);
    return $dest_img;
  }
  /**
   * 创建目录
   * @param String $path
   * @return Boolean
   */
  private function create_dirs($path){
    if(!is_dir($path)){
      return mkdir($path, 0777, true);
    }
    return true;
  }
  /** hex颜色转rgb颜色
   * @param String $color hex颜色
   * @return Array
   */
  private function hex2rgb($hexcolor){
    $color = str_replace('#', '', $hexcolor);
    if (strlen($color) > 3) {
      $rgb = array(
        'r' => hexdec(substr($color, 0, 2)),
        'g' => hexdec(substr($color, 2, 2)),
        'b' => hexdec(substr($color, 4, 2))
      );
    } else {
      $r = substr($color, 0, 1) . substr($color, 0, 1);
      $g = substr($color, 1, 1) . substr($color, 1, 1);
      $b = substr($color, 2, 1) . substr($color, 2, 1);
      $rgb = array(
        'r' => hexdec($r),
        'g' => hexdec($g),
        'b' => hexdec($b)
      );
    }
    return $rgb;
  }
  /** 获取图片类型 
   * @param String $file 图片路径 
   * @return int 
   */ 
  private function get_file_ext($file){
    $filename = basename($file);
    list($name, $ext)= explode('.', $filename);
    $ext_type = 0;
    switch(strtolower($ext)){
      case 'jpg':
      case 'jpeg':
        $ext_type = 2;
        break;
      case 'gif':
        $ext_type = 1;
        break;
      case 'png':
        $ext_type = 3;
        break;
    }
    return $ext_type;
  }
} // class end
?>

demo.php


<?php
require 'PHPQRCode.class.php';
$config = array(
    'ecc' => 'H',  // L-smallest, M, Q, H-best
    'size' => 12,  // 1-50
    'dest_file' => 'qrcode.png',
    'quality' => 90,
    'logo' => 'logo.jpg',
    'logo_size' => 100,
    'logo_outline_size' => 20,
    'logo_outline_color' => '#FFFF00',
    'logo_radius' => 15,
    'logo_opacity' => 100,
);
// 二维码内容
$data = 'https://www.jb51.net/';
// 创建二维码类
$oPHPQRCode = new PHPQRCode();
// 设定配置
$oPHPQRCode->set_config($config);
// 创建二维码
$qrcode = $oPHPQRCode->generate($data);
// 显示二维码
echo '<img src="'.$qrcode.'?t='.time().'">';
?>

生成的二维码效果图:

完整源码下载:请点击此处前往本站下载页面。

此外,推荐两款实用的在线二维码生成工具供参考:

在线生成二维码工具(加强版) 点击使用

希望上述内容能对您的PHP编程工作有所助益。

上一篇
PHP类和对象相关函数详解

本文介绍了PHP中用于处理类和对象的常用函数。包括判断类、接口、方法和属性是否存在,获取类名、父类名、方法及属性列表,以及判断变量类型等。这些函数在面向对象编程中非常有用,可以帮助开发者更好地管理和操作类和对象。

下一篇
PHP防范SQL注入的四种核心方法详解

PHP程序常面临SQL注入风险,尽管早期版本通过magic_quotes_gpc提供基础防护,但黑客可通过编码绕过。本文详解四种有效防御手段:首先处理magic_quotes_gpc状态并配合addslashes函数进行字符转义;其次对整型ID等变量强制类型转换;再次在SQL查询中为字符串变量添加单引号以隔离执行逻辑;最后利用URL重写技术实现伪静态化,从源头减少参数暴露,全面提升系统安全性。

相关文章

更多
PHP后端生成推广海报:背景图与二维码合成方案

在H5或小程序环境中,前端Canvas存在兼容性局限,推荐采用后端PHP直接生成包含背景、二维码及文字的海报。本文介绍利用PHP GD库将服务器本地读取的背景图与动态生成的二维码图像进行合并,支持自定义位置、字号及透明度,最终输出PNG或JPG格式图片供前端调用分享。

2025.05.19 942
怎么在PHP中生成带Logo的自定义二维码

使用 endroid/qr-code 库,通过 Logo::fromString() 加载图片并传入 setLogo() 方法即可生成带 Logo 的二维码。

2026.12.03 765
PHP批量生成带Logo和自定义颜色的二维码配置指南

使用 endroid/qr-code 库,通过循环遍历数据并调用 Writer::writeDataUri() 或 writeString() 方法,配合 Logo::createFromPath() 和颜色配置对象即可批量生成。

2025.05.24 392
PHP利用Imagick扩展实现微信海报合成与圆角处理

本文介绍如何使用PHP的Imagick扩展库,将微信用户头像、专属二维码及背景图合成为一张个性化海报。核心步骤包括通过公众号接口获取带参数二维码Ticket,利用Imagick加载并缩放二维码,对头像应用圆角滤镜,最后将各元素叠加合成最终图片输出。

2026.01.05 233
PHP生成二维码的两种方法:Google API与php QR Code

本文介绍利用Google开放接口和php QR Code类库在PHP中生成二维码的两种实现方式。前者通过调用Google Chart API,支持设置尺寸、纠错级别及边距;后者需下载第三方类库包,提供本地化生成能力。文中分别给出了基于GET请求封装函数和POST请求使用cURL的具体代码示例,帮助开发者快速掌握相关技术。

2026.07.05 203

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。