Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP HTML image output

Tags:

html

php

image

gd

In the PHP manual for base64_encode() I saw the following script for outputting an image.

<?php

$imgfile = "test.gif";

$handle = fopen($filename, "r");

$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));

echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" />';

?>

But how can you output an image dynamically created with GD?

I've tried this:

$im = imagecreatetruecolor(400, 400);

imagefilledrectangle($im, 0, 0, 200, 200, 0xFF0000);
imagefilledrectangle($im, 200, 0, 400, 200, 0x0000FF);
imagefilledrectangle($im, 0, 200, 200, 400, 0xFFFF00);
imagefilledrectangle($im, 200, 200, 400, 400, 0x00FF00);

echo '<img src="data:image/png;base64,'.base64_encode(imagepng($im)).'" />';

Why doesn't that work?

It seems to work in IE but not Firefox. How can I make it cross-browser?

like image 911
Mark Lalor Avatar asked Sep 12 '10 13:09

Mark Lalor


People also ask

How do I display an image in HTML?

To insert image in an HTML page, use the <img> tags. It is an empty tag, containing only attributes since the closing tag is not required. Just keep in mind that you should use the <img> tag inside <body>… </body> tag.

How do I echo an image in PHP?

You cant echo an image using PHP. echo is for strings only. However, you can echo the image source - img src="" Just make sure you put the picture extension at the end of the file you are grabbing.

How can I view uploaded image in PHP?

$_FILES["file"]["name"]. "<br>"; $image=$_FILES["file"]["name"]; /* Displaying Image*/ $img="upload/". $image; echo '<img src= "upload/". $img>'; } } } else { echo "Invalid file"; } ?>


1 Answers

Ok, sorry, I was thinking too fast :)

imagepng() will output raw data stream directly to the browser, so you must use ob_start() and other output buffering handles to obtain it.

Here you are:

ob_start();
imagepng($yourGdImageHandle);
$output = ob_get_contents();
ob_end_clean();

That is - you need to use $output variable for you base64_encode() function.

like image 164
Tomasz Kowalczyk Avatar answered Oct 23 '22 05:10

Tomasz Kowalczyk