Mona Coder Mona Coder - 2 months ago 6
HTML Question

PHP - Create & Render Multiple Image On The Fly

Can you please take a look at this code and let me know why I am not able to render generated images to the page on the fly?

<?php
for ($i = 0; $i <= 3; $i++) {
$im = imagecreatetruecolor(320, 80);
$text_color = imagecolorallocate($im, 255, 255, 255);
imagestring($im, 20, 20, 5, "Test App", $text_color);

$img = imagejpeg($im, 'Test.jpg');

echo '<div class="map"><img src="'.$img.'" class="img-responsive" alt="Cinque Terre"></div>';

imagedestroy($im);
}
?>


what I am getting in the output now is

enter image description here

while the
src
attributes of the images are
1
!

enter image description here

Answer

Capture the byte stream, then convert. You'll need to base64_encode the raw byte. Then use it in the image tag:

Basic idea:

for ($i = 0; $i <= 3; $i++) {
    ob_start(); // begin capture
    $im = imagecreatetruecolor(320, 80);
    $text_color = imagecolorallocate($im, 255, 255, 255);
    imagestring($im, 20, 20, 5,  "Test App " . ($i + 1), $text_color);

    $img = imagejpeg($im, null, 100);
    $raw = ob_get_clean(); // get

    echo '<div class="map"><img src="data:image/jpeg;base64,'.base64_encode($raw).'" class="img-responsive" alt="Cinque Terre"></div>';
}
Comments