Wolfgang Müller
Wolfgang Müller

Reputation: 386

How to show image GD Resource in twig template

I have generated a GD Image Resource from the Zend Barcode Object. How can I render this resource in a twig template?

Upvotes: 0

Views: 860

Answers (1)

Yanis-git
Yanis-git

Reputation: 7875

hello this code do the trick :

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).'">';

Explication :

imagejpeg() or imagepng() receive as parameter gd image ressource and print it. Here we play around with ob_*function to capture this output in variable instead of print it. Then you can do what ever you want with this data. On my code i have done both possibility :

  • Save it in static file.
  • Directly print it as base64 image inside my html.

Upvotes: 1

Related Questions