需求:按网址数组生成二维码,返回相应的base64数据
插件类:phpqrcode.php
phpqrcode.php下载链接:phpqrcode.php下载链接
插件原有的方法实现起来都会把生成的图片输出到浏览器,不符合我只要二维码的base64数据,不自动显示的需求
所以开始上网找资料,最后看到别人的做法后灵机一动,自己修改phpqrcode.php类文件,增加一些不直接输出显示二维码的方法不就行了
1.在QRcode类中新增方法pngString
public static function pngString($text, $outfile = false, $level = QR_ECLEVEL_L, $size = 3, $margin = 4, $saveandprint=false)
{
$enc = QRencode::factory($level, $size, $margin);
return $enc->encodePNGString($text, $outfile, $saveandprint=false);
}
2.在QRencode类中新增方法encodePNGString
public function encodePNGString($intext, $outfile = false,$saveandprint=false)
{
try {
ob_start();
$tab = $this->encode($intext);
$err = ob_get_contents();
ob_end_clean();
if ($err != '')
QRtools::log($outfile, $err);
$maxSize = (int)(QR_PNG_MAXIMUM_SIZE / (count($tab)+2*$this->margin));
QRimage::pngString($tab, $outfile, min(max(1, $this->size), $maxSize), $this->margin,$saveandprint);
} catch (Exception $e) {
QRtools::log($outfile, $e->getMessage());
}
}
3.在QRimage类中新增方法pngString
public static function pngString($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE)
{
$image = self::image($frame, $pixelPerPoint, $outerFrame);
if ($filename === false) {
ImagePng($image);
} else {
if($saveandprint===TRUE){
ImagePng($image, $filename);
ImagePng($image);
}else{
ImagePng($image, $filename);
}
}
ImageDestroy($image);
}
4.引入phpqrcode.php后,调用QRcode类的pngString方法
public function getQRcode($url){
//打开缓冲区
ob_start();
//生成二维码图片
$returnData = QRcode::pngString($url,false, "H", 3, 1);
//这里就是把生成的图片流从缓冲区保存到内存对象上,使用base64_encode变成编码字符串,通过json返回给页面。
$imageString = base64_encode(ob_get_contents());
//关闭缓冲区
ob_end_clean();
$str = "data:image/png;base64,".$imageString;
return $str;
}
$virtualHost = Array(
['name'=>'baidu', 'host'=>'https://www.baidu.com/'],
['name'=>'csdn', 'host'=>'https://www.csdn.net/'],
);
require_once dirname(__FILE__)."/plugins/phpqrcode/phpqrcode.php";
foreach($virtualHost as $k => $v){
$virtualHost[$k]['qrcode'] = base::getQRcode($virtualHost[$k]['host']);
}
这样子,数组里面的qrcode属性就是二维码的base64数据了
直接把它赋值给img的src属性就行了
foreach($virtualHost as $v){
echo "<img src='{$v['qrcode']}' alt='{$v[name]}' />";
}