Home > Enterprise >  How to how image in HTML without saving to file
How to how image in HTML without saving to file

Time:11-08

I create an image with imagestring and a text by PHP. I know imagepng($image) without $filepath shows image in web page, but I want to know is it possible to show image by HTML (to use divs and tags) without saving image to a file by imagepng(). I use PHP code below:

<?php
$image = imagecreatetruecolor(100, 100);
$white = imagecolorallocate ($image,255,255,255);
$black = imagecolorallocate ($image,0,0,0);
imagefill($image,0,0,$white);
imagestring($image, 5, 31, 50, 'text', $black );
header('Content-Type: image/png');
imagepng($image);
#phpinfo();
?>

<!DOCTYPE html>
<html>
<div>
<!-- want to show image created by imagestring() here -->
</div>
</html>

CodePudding user response:

Try this out

<?php
$image = imagecreatetruecolor(100, 100);
$white = imagecolorallocate ($image,255,255,255);
$black = imagecolorallocate ($image,0,0,0);
imagefill($image,0,0,$white);
imagestring($image, 5, 31, 50, 'text', $black );

ob_start();
imagepng($image);
$imagedata = ob_get_clean();
$b64image = base64_encode($imagedata);

$html = <<<EOD
<!DOCTYPE html>
<html>
<div> 
<img src="data:image/png;base64, $b64image" /> 
</div>
</html>
EOD;

echo $html;
?>
  • Related