2017-04-17 226 views
0

我正在使用CakePHP 3.4框架爲我的應用程序和endroid/qrcode生成器。php qr代碼無法正確顯示

在控制器中,我使用

use Endroid\QrCode\QrCode; 

$qrCode = new QrCode(); 
$qrCode 
    ->setText('Life is too short to be generating QR codes') 
    ->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('Scan the code') 
    ->setLabelFontSize(16) 
    ->setImageType(QrCode::IMAGE_TYPE_PNG) 
; 
$this->set(compact('qrCode')); 

,並鑑於

header('Content-Type: '.$qrCode->getContentType()); 
$qrCode->render(); ?> 

但這渲染爲

enter image description here

可能是什麼問題,這是不顯示qr圖像?

+0

你只是只渲染圖像?如果是這樣,您應該使用Response對象從控制器返回圖像。 – chrisShick

+0

根據文檔提供者錯誤創建響應'Response class not found' –

回答

1

如果你的控制器方法只返回QR碼圖像,你應該沒問題,將下面的代碼添加到你的控制器。

編輯:檢查了您正在使用的圖書館的文檔。根據文檔,您必須使用Writer。請閱讀。未經測試:

use Endroid\QrCode\QrCode; 
use Endroid\QrCode\Writer\PngWriter; 
... 
$response = $this->response; 

$response = $response->withType($qrCode->getContentType(PngWriter::class)) 
    ->withStringBody($qrCode->writeString(PngWriter::class)); 

// Return response object – you won't have to have a View for this method 
return $response; 

// $this->set(...) from your code is obsolete 

在View中發送標題似乎是錯誤的,因爲它是一個Controller任務。

編輯:然後,您可以使用控制器方法作爲圖像源,即i。 Ë:

<img src="/path/to/your/controller/action" alt="QR Code here"> 

如果您希望QR代碼以顯示這種方法的一個視圖中,而不是返回的形象,你既可以:

一)寫入生成的QR代碼添加到您的文件系統作爲一個圖像文件

使用庫的Endroid\QrCode\QrCode::writeFile()方法,而不是返回Response對象。

B)使用數據URI作爲寫在文件

$writer = new DataUriWriter($qrCode); 
$dataUri = $writer->writeString(); 

我真的不知道,如果你連看Docs

+0

'withStringBody()';-) – ndm

+0

謝謝@ndm - 沒有注意到這一點。 ;) – Mary

+0

感謝@瑪麗你說過,我不需要對這種方法有一個看法。但是我只想在視圖上顯示QR。即,在'qrcode.ctp'視圖和'qrcode()'響應中調用'qrcode()'的方式創建 –