带有流明的二维码生成器 API


QR Code Generator API with Lumen

我正在开发一个API来生成带有Lumen和Endroid/QrCode包的QR码。

如何通过 HTTP 响应发送二维码,这样我就不必将二维码保存在我的服务器上?

我可以在单个索引.php文件上执行此操作,但是如果我在Lumen框架(或Slim)上执行此操作,我只会在页面上打印字符。

单独的索引.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 }}">

希望这能帮助任何人遇到这个问题。