Displaying an image created with imagecreatefromstring Displaying an image created with imagecreatefromstring php php

Displaying an image created with imagecreatefromstring


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.


<?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.


I think you can do something like this...

$src = "data:image/gif;base64," . $imageData ;echo "<img src=\"$src\" alt=\"the image\" />";