2016-02-12 42 views
0

我正在開發一個API來生成帶有流明和Endroid/QrCode包的QR碼。帶有流明的QR碼生成器API

如何通過HTTP響應發送QR碼,讓我沒有保存QR碼我的服務器上?

我可以做一個單一的index.php文件,但如果我這樣做的流明框架(或修身爲好)我只是得到打印的頁面上的人物。

獨立的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

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']); 
}); 
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); 

此代碼返回,我在一個簡單的圖像已插入

<img src="{{ $base64Qr }}"> 

希望這將幫助任何人遇到這樣的問題的Base64編碼字符串。