PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How to show image GD Resource in twig template

 October 10, 2022     gd, image, symfony, twig     No comments   

Issue

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


Solution

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.


Answered By - Yanis-git
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing