2017-04-17 230 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()'的方式创建 –