我正在开发一个用Lumen和Endroid/QrCode包生成二维码的API。
如何通过HTTP响应发送二维码,以便不必将二维码保存在服务器上?
我可以在单个index.php文件上做,但如果我在Lumen框架(或Slim )上做,我只会在页面上打印字符。
单独的index.php:
$qr_code = new QRCode();
$qr_code
->setText("Sample Text")
->setSize(300)
->setPadding(10)
->setErrorCorrection('high')
->render();效果很好!
使用Lumen,我这样做:
$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());
});但它不起作用。
我该怎么做呢?
发布于 2016-02-13 07:13:39
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']);
});发布于 2016-04-22 18:33:05
这是个老问题,但今天我也遇到了同样的问题。为了在管腔视图中渲染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 }}">希望这篇文章能帮助任何遇到这个问题的人。
https://stackoverflow.com/questions/35368026
复制相似问题