[英]QR Code Generator API with Lumen
我正在開發一個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());
});
而且不起作用。
我該怎么做?
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']);
});
老問題了,但是今天我也遇到了同樣的問題。 為了在流明的視圖中呈現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 }}">
希望這可以幫助任何人遇到這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.