php在线生成二维码(四色和单色)

1. 前言

使用该扩展前,先确认其 PHP 版本要求,endroid/qr-code 4.x 需要 PHP 版本 7.4+

Packagist 传送地址: https://packagist.org/packages/endroid/qr-code

使用前需要检查下是否启用了 gd2 扩展,对于 endroid/qr-code 版本选择,参考扩展包文档对 PHP 版本的要求

2. 安装扩展

执行 composer 命令安装 endroid/qr-code 扩展

composer require endroid/qr-code

3. 生成二维码

使用 Builder 生成器:

use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

$result = Builder::create()
    ->writer(new PngWriter())
    ->writerOptions([])
    // 二维码文本
    ->data('https://www.itqaq.com')
    // 内容编码
    ->encoding(new Encoding('UTF-8'))
    // 容错等级(越高二维码越密集)
    ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
    // 二维码内容区域大小
    ->size(300)
    // 二维码内容外边距大小
    ->margin(10)
    // 二维码内容圆形块尺寸模型
    ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
    // 二维码中间区域logo图片
    ->logoPath(__DIR__ . '/3.png')
    ->logoResizeToWidth(100)
    ->logoResizeToHeight(100)
    // 二维码下方文字
    ->labelText('长按识别二维码')
    ->labelFont(new NotoSans(20))
    ->labelAlignment(new LabelAlignmentCenter())
    // 验证读取器(默认情况下禁用)
    ->validateResult(false)
    // 执行生成器
    ->build();

不使用 Builder 生成器:

use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

$writer = new PngWriter();
$qrCode = QrCode::create('https://www.itqaq.com')
    // 内容编码
    ->setEncoding(new Encoding('UTF-8'))
    // 容错等级
    ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
    // 内容区域大小
    ->setSize(300)
    // 内容区域外边距
    ->setMargin(10)
    // 内容圆形块尺寸模型
    ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
    // 内容颜色
    ->setForegroundColor(new Color(0, 0, 0))
    // 背景颜色
    ->setBackgroundColor(new Color(255, 255, 255));
// 二维码logo logo
$logo = Logo::create(__DIR__ . '/3.png')
    ->setResizeToWidth(50);
// 二维码下方文字 label
$label = Label::create('Label')
    ->setTextColor(new Color(255, 0, 0));
// 生成二维码数据对象(后面两个参数都是可选的)
$result = $writer->write($qrCode, $logo, $label);

实际开发中,源码

<?php

namespace App\Admin\Controllers;
use Encore\Admin\Controllers\AdminController;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelMedium;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelQuartile;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use Illuminate\Http\Request; 
use Endroid\QrCode\Color\Color;

class QrcodeController extends AdminController
{
  public function getthisqrcode(Request $request){
        $data=$request->input('data');
        $contentsId=$request->input('contentsId');
        if($contentsId){
            $data=$data.'&contentsId='.$contentsId;
        }
        $ecc=$request->input('ecc');
        $size=$request->input('size');
        $margin=$request->input('margin');
        $color=$request->input('color');//例rgb(0,0,0);
        $bgcolor=$request->input('bgcolor');//例rgb(255,255,255);
        $color=str_replace('rgb(','',$color);
        $color=str_replace(')','',$color);
        $colorarr=explode(",",$color);
        $bgcolor=str_replace('rgb(','',$bgcolor);
        $bgcolor=str_replace(')','',$bgcolor);
        $bgcolorarr=explode(",",$bgcolor);
        $logopath=$request->input('logopath');
        $logosize=$request->input('logosize',50);
        // var_dump($colorarr);var_dump($bgcolorarr);var_dump(intval($colorarr[0]));exit;
        
        $text=$request->input('text',"This is the label2");
        if($ecc=="H"){
            $level=new ErrorCorrectionLevelHigh();
        }elseif($ecc=="M"){
            $level=new ErrorCorrectionLevelMedium();
        }elseif($ecc=="Q"){
            $level=new ErrorCorrectionLevelQuartile();
        }elseif($ecc=="L"){
            $level=new ErrorCorrectionLevelLow();
        }
        
        if(!$logopath){
            $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data(urldecode($data))
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel($level)
            ->size($size)
            ->margin($margin)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            // ->logoPath(__DIR__.'/assets/symfony.png')
            ->foregroundColor(new Color(intval($colorarr[0]),intval($colorarr[1]),intval($colorarr[2])))
            ->backgroundColor(new Color(intval($bgcolorarr[0]),intval($bgcolorarr[1]),intval($bgcolorarr[2])))
            // ->labelText($text)
            // ->labelFont(new NotoSans(20))
            // ->labelAlignment(new LabelAlignmentCenter())
            ->validateResult(false)
            ->build();
        }else{
            $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data(urldecode($data))
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel($level)
            ->size($size)
            ->margin($margin)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->logoPath("http://www.xxxx.com/".$logopath)
            ->logoResizeToWidth($logosize)
            ->logoResizeToHeight($logosize)
            ->foregroundColor(new Color(intval($colorarr[0]),intval($colorarr[1]),intval($colorarr[2])))
            ->backgroundColor(new Color(intval($bgcolorarr[0]),intval($bgcolorarr[1]),intval($bgcolorarr[2])))
            // ->labelText($text)
            // ->labelFont(new NotoSans(20))
            // ->labelAlignment(new LabelAlignmentCenter())
            ->validateResult(false)
            ->build();
        }
        
        header('Content-Type: '.$result->getMimeType());
        echo $result->getString();
        exit();
    }

}

4. 输出二维码

以下是三种输出二维码的方式,根据项目场景选择合适的方式即可

// 直接输出在浏览器中
// ob_end_clean(); //处理在TP框架中显示乱码问题
// header('Content-Type: ' . $result->getMimeType());
// echo $result->getString();
// exit();//phpqrcode生成二维码输出时出现乱码

// 将二维码图片保存到本地服务器
// $result->saveToFile(__DIR__ . '/qrcode.png');

// 返回 base64 格式的图片
$dataUri = $result->getDataUri();
echo "<img src='{$dataUri}'>";

5.加上前端看效果

以上二维码为四色二维码,印刷时为了不使二维码失色,一般二维码为单色二维码,那么如何生成单色二维码

转单色源码



<?php

namespace App\Admin\Controllers;
use Encore\Admin\Controllers\AdminController;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelMedium;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelQuartile;
use Endroid\QrCode\Label\Alignment\LabelAlignmentCenter;
use Endroid\QrCode\Label\Font\NotoSans;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use Illuminate\Http\Request; 
use Endroid\QrCode\Color\Color;
use Imagick;
class QrcodeController extends AdminController
{
  public function getthisqrcodedan(Request $request){
        $data=$request->input('data');
        $contentsId=$request->input('contentsId');
        if($contentsId){
            $data=$data.'&contentsId='.$contentsId;
        }
        $ecc=$request->input('ecc');
        $size=$request->input('size');
        $margin=$request->input('margin');
        $color="rgb(0, 0, 0)";
        $bgcolor="rgb(255, 255, 255)";
        $color=str_replace('rgb(','',$color);
        $color=str_replace(')','',$color);
        $colorarr=explode(",",$color);
        $bgcolor=str_replace('rgb(','',$bgcolor);
        $bgcolor=str_replace(')','',$bgcolor);
        $bgcolorarr=explode(",",$bgcolor);
        $logopath=$request->input('logopath');
        $logosize=$request->input('logosize',50);
        // var_dump($colorarr);var_dump($bgcolorarr);var_dump(intval($colorarr[0]));exit;
        
        $text=$request->input('text',"This is the label2");
        if($ecc=="H"){
            $level=new ErrorCorrectionLevelHigh();
        }elseif($ecc=="M"){
            $level=new ErrorCorrectionLevelMedium();
        }elseif($ecc=="Q"){
            $level=new ErrorCorrectionLevelQuartile();
        }elseif($ecc=="L"){
            $level=new ErrorCorrectionLevelLow();
        }
        
        if(!$logopath){
            $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data(urldecode($data))
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel($level)
            ->size($size)
            ->margin($margin)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            // ->logoPath(__DIR__.'/assets/symfony.png')
            ->foregroundColor(new Color(intval($colorarr[0]),intval($colorarr[1]),intval($colorarr[2])))
            ->backgroundColor(new Color(intval($bgcolorarr[0]),intval($bgcolorarr[1]),intval($bgcolorarr[2])))
            // ->labelText($text)
            // ->labelFont(new NotoSans(20))
            // ->labelAlignment(new LabelAlignmentCenter())
            ->validateResult(false)
            ->build();
        }else{
            $result = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data(urldecode($data))
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel($level)
            ->size($size)
            ->margin($margin)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->logoPath("http://www.xxxx.com/".$logopath)
            ->logoResizeToWidth($logosize)
            ->logoResizeToHeight($logosize)
            ->foregroundColor(new Color(intval($colorarr[0]),intval($colorarr[1]),intval($colorarr[2])))
            ->backgroundColor(new Color(intval($bgcolorarr[0]),intval($bgcolorarr[1]),intval($bgcolorarr[2])))
            // ->labelText($text)
            // ->labelFont(new NotoSans(20))
            // ->labelAlignment(new LabelAlignmentCenter())
            ->validateResult(false)
            ->build();
        }
        
        // header('Content-Type: '.$result->getMimeType());
        // echo $result->getString();
     
        $uq=uniqid();
        $filepath="./excel/ewm/one/".date("Y-m-d");
        $this->createfolder($filepath);
        $filename=$filepath.'/'.$uq.'.png';
        $result->saveToFile($filename);
        $this->dealimage($filename);
        $this->showImage($filename);
        // return "https://www.xxx.com/excel/ewm/".$uq.'.png';
        exit();
    }
    //转单色
    public function dealimage($filename){
        $imagick = new Imagick();
        $imagick->readImage($filename);
        $imagick->setImageType(Imagick::IMGTYPE_GRAYSCALE);
        $imagick->writeImage($filename);
    }
    
    public function showImage($img){
        $mime=image_type_to_mime_type(exif_imagetype($img));//获取图片的MIME类型
        header('Content-Type:'.$mime);
        readfile($img);
    }
}