~~~
<?php
namespace app\utils;
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;
class QrcodeServer
{
/**
* 二维码生成 并保存为图片
* @param $userId 用户ID
* @param int $size 二维码大小
* @throws \Exception
*/
public static function generate($username,$size=300){
$root_path = app()->getRootPath();
$result = Builder::create()
->writer(new PngWriter())
->writerOptions([])
->data('only_code:'.$username)
->encoding(new Encoding('UTF-8'))
->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
->size($size)
->margin(10)
->roundBlockSizeMode(new RoundBlockSizeModeMargin())
// ->logoPath($root_path.'/public/img/1.png')
->labelText('')
->labelFont(new NotoSans(20))
->labelAlignment(new LabelAlignmentCenter())
->build();
// Directly output the QR code
// header('Content-Type: '.$result->getMimeType());
$codeName = time().rand(100,999);
// Save it to a file
$path = $root_path.'/public/qrcode/qrcode_'.$codeName.'.png';
//生成成功
$result->saveToFile($path);
// base64
//$dataUri = $result->getDataUri();
//没有开启oss
if(env('oss.open') !== true){
return '/qrcode/qrcode_'.$codeName.'.png';
}
if($result){
$res = AliOss::simpleUpload($path,$codeName.'.png',2);
if($res){
@unlink($path);
return $res;
}
return false;
}
return false;
}
}
~~~