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

Monday, October 10, 2022

[FIXED] How can I output a dynamically created image directly within a HTML page?

 October 10, 2022     gd, http-headers, php     No comments   

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)
  • 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