Issue
I have a HTML page. On this page I want to display a dynamically created PNG image without saving it to a file first.
When I simply try to create the image within the page, of course I get an error stating that headers where already sent.
Sample code:
<!doctype html>
<html>
<head>
<title>A Test Page</title>
</head>
<body>
<h1>An Image</h1>
<?php
$im = imagecreatetruecolor(100, 100);
$white = ImageColorAllocate ($im, 255, 255, 255);
$black = ImageColorAllocate ($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 50, 50, $white);
imagefilledrectangle($im, 0, 50, 50, 100, $black);
imagefilledrectangle($im, 50, 0, 100, 50, $black);
imagefilledrectangle($im, 50, 50, 100, 100, $white);
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
</body>
</html>
Solution
What you could do is buffering the image in a variable and then encode the img as base64:
ob_start();
imagepng($im);
$img_content = ob_get_contents();
ob_end_clean();
$dataUri = "data:image/png;base64," . base64_encode($img_content);
echo '<img src="' . $dataUri . '">';
Answered By - user1915746 Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.