如何在树枝模板中显示图像 GD 资源
How to show image GD Resource in twig template
我已经从 Zend 条码对象生成了 GD 图像资源。我如何在树枝模板中呈现此资源?
你好,这段代码可以解决问题:
require 'vendor/autoload.php';
use Zend\Barcode\Barcode;
// Only the text to draw is required
$barcodeOptions = array('text' => 'ZEND-FRAMEWORK');
// No required options
$rendererOptions = array();
$image = Barcode::draw(
'code39',
'image',
$barcodeOptions,
$rendererOptions
);
// By default, imagepng will print on the output file your image.
// Here we play around with ob_* to catch this output and store it on $contents variable.
ob_start();
imagepng($image);
$contents = ob_get_contents();
ob_end_clean();
// Save as test.png your current barcode.
file_put_contents('test.png', $contents);
// Display img tag with base64 encoded barcode.
echo '<img src="data:image/png;base64,'.base64_encode($contents).'">';
解释:
imagejpeg()
或 imagepng()
作为参数接收 gd 图像资源并打印它。在这里,我们使用 ob_*
函数来捕获变量中的输出而不是打印它。然后你可以用这些数据做任何你想做的事。在我的代码中,我已经完成了两种可能性:
- 保存在静态文件中。
- 直接在我的html.
里面打印成base64图片
我已经从 Zend 条码对象生成了 GD 图像资源。我如何在树枝模板中呈现此资源?
你好,这段代码可以解决问题:
require 'vendor/autoload.php';
use Zend\Barcode\Barcode;
// Only the text to draw is required
$barcodeOptions = array('text' => 'ZEND-FRAMEWORK');
// No required options
$rendererOptions = array();
$image = Barcode::draw(
'code39',
'image',
$barcodeOptions,
$rendererOptions
);
// By default, imagepng will print on the output file your image.
// Here we play around with ob_* to catch this output and store it on $contents variable.
ob_start();
imagepng($image);
$contents = ob_get_contents();
ob_end_clean();
// Save as test.png your current barcode.
file_put_contents('test.png', $contents);
// Display img tag with base64 encoded barcode.
echo '<img src="data:image/png;base64,'.base64_encode($contents).'">';
解释:
imagejpeg()
或 imagepng()
作为参数接收 gd 图像资源并打印它。在这里,我们使用 ob_*
函数来捕获变量中的输出而不是打印它。然后你可以用这些数据做任何你想做的事。在我的代码中,我已经完成了两种可能性:
- 保存在静态文件中。
- 直接在我的html. 里面打印成base64图片