我正在开发一个API,用Lumen和Endroid / QrCode包生成QR码。
如何通过HTTP响应发送QR码,以便我不必在服务器上保存QR码?
我可以在一个index.php文件上执行此操作,但如果我在Lumen框架(或Slim)上执行此操作,我只会在页面上打印字符。
分开index.php:
$qr_code = new QRCode();
$qr_code
->setText("Sample Text")
->setSize(300)
->setPadding(10)
->setErrorCorrection('high')
->render();
效果很好!
使用流明我正在这样做:
$app->get('/qrcodes',function () use ($app) {
$qr_code = new QrCode();
$code = $qr_code->setText("Sample Text")
->setSize(300)
->setPadding(10)
->setErrorCorrection('high');
return response($code->render());
});
它不起作用。
我该怎么做?
答案 0 :(得分:0)
QRCode::render()
方法实际上并不返回QR码字符串;它返回QR对象。在内部,render
方法调用本机PHP imagepng()
函数,该函数立即将QR图像流式传输到浏览器,然后返回$this
。
你可以尝试两件事。
首先,您可以尝试像处理普通索引文件一样处理此路由(但是,我正在添加对header()
的调用):
$app->get('/qrcodes',function () use ($app) {
header('Content-Type: image/png');
$qr_code = new QrCode();
$qr_code->setText("Sample Text")
->setSize(300)
->setPadding(10)
->setErrorCorrection('high')
->render();
});
另一个选择是捕获缓冲区中的输出,并将其传递给response()
方法:
$app->get('/qrcodes',function () use ($app) {
// start output buffering
ob_start();
$qr_code = new QrCode();
$qr_code->setText("Sample Text")
->setSize(300)
->setPadding(10)
->setErrorCorrection('high')
->render();
// get the output since last ob_start, and close the output buffer
$qr_output = ob_get_clean();
// pass the qr output to the response, set status to 200, and add the image header
return response($qr_output, 200, ['Content-Type' => 'image/png']);
});
答案 1 :(得分:0)
老问题,但今天我遇到了同样的问题。为了在流明的视图中呈现QR,我使用:
$data['base64Qr']=$qrCode
->setText("sample text")
->setSize(300)
->setPadding(10)
->setErrorCorrection('high')
->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
->setLabel('sample label')
->setLabelFontSize(16)
->getDataUri();
return view('view',$data);
此代码返回我在简单图像中插入的Base64字符串
<img src="{{ $base64Qr }}">
希望这可以帮助任何人遇到这个问题。