Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying an image created with imagecreatefromstring

Tags:

html

php

image

jpeg

gd

Let's say I have the code that looks something like:

<?PHP

//
//... stuff here
//

$im = imagecreatefromstring( $imageData );

echo "<img src=" . /* what goes here? */ . "alt=\"the image\" />";


//
// more stuff here
//
?>

What do I replace /* what goes here? */ with so my image data will display?

Thank you.

like image 796
ericg Avatar asked Aug 05 '11 18:08

ericg


2 Answers

What do I replace /* what goes here? */ with so my image data will display?

The location you highlighted is the so called src attribute of the img HTML-tagDocs. The value is a so called URIDocs.

In your case you want that URI to point to the image data in question. You have not specified which type the image should be output as, so I will assume it's a PNG image in the following example.

You now need to convert your image data into an URI. The most straight forward URI to create from the image data is a so called data: URIWikipedia:

<?PHP

//
//... stuff here
//

$im = imagecreatefromstring( $imageData );

ob_start();
imagepng($img);
$png = ob_get_clean();
$uri = "data:image/png;base64," . base64_encode($png);

echo "<img src=" . $uri /* URI goes here */ . " alt=\"the image\" />";

//
// more stuff here
//
?>

Even this is the most straight forward way, it is not always recommended to do so because the image data will be returned with the HTML to the browser. If the image is large, this is commonly considered an overhead.

Instead of using the data: URI you can place any other URI in there as well, for example a HTTP URI that is pointing to a PHP script on your server that is returning the image. Such a script can be very simple:

<?php
$img = imagecreatefromstring($string);
header('Content-type: image/png');
imagepng($img);

This is comparable to what Marc B suggested, see his answer as well.

like image 155
hakre Avatar answered Sep 30 '22 18:09

hakre


<?php

$img = imagecreatefromstring($string);

header('Content-type: image/jpeg');
imagejpeg($img);

should be all you need. Doing it with the image tag as you are, you'd need to output the image to a temporary file and point the image tag at that (which incurs a second HTTP request), or use a data url.

like image 20
Marc B Avatar answered Sep 30 '22 16:09

Marc B