Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: recreate and display an image from binary data

Is it possible to recreate images from binary data (process them if needed) and display them, all in the same script? Something like

// get and display image 1: $imagedata1 = file_get_contents('assets/test.png'); $imagedata1 = process_using_gd_or_something($imagedata1);  echo "<img src={$imagedata1} >"; // <-- IS THIS (OR EQUIVALENT) POSSIBLE?  // get and display image 2: //etc... 

I want to avoid storing the images to to disk after processing and getting them from there, or using an external script...

like image 337
Cambiata Avatar asked Jan 15 '10 09:01

Cambiata


People also ask

How to display binary image in PHP?

Format. The 'data_uri' function defines the 'contents', 'base64' and returns the data and its encoded value. This function is called by passing an image to it, thereby recreating it and displaying it in the form of binary data. Note − This can be used to avoid storing the images to the disk after processing them.

How can I write binary data to a file in PHP?

For writing binary data to a file, you can use the functions pack() and unpack() . Pack will produce a binary string. As the result is a string, you can concatenate the ints into a single string. Then write this string as a line to your file.

Does PHP use binary content?

Unlike writing to a text file that has a single function to accomplish both tasks, reading files in PHP is separated into two functions, depending on whether you are reading binary data(fgets() or fread()).


1 Answers

You can do this using a data URI in the image src attribute.

The format is: data:[<MIME-type>][;charset="<encoding>"][;base64],<data>

This example is straight from the Wikipedia page on data URIs:

<?php function data_uri($file, $mime)  {     $contents = file_get_contents($file);   $base64   = base64_encode($contents);    return ('data:' . $mime . ';base64,' . $base64); } ?>  <img src="<?php echo data_uri('elephant.png','image/png'); ?>" alt="An elephant" /> 
like image 135
Ben James Avatar answered Sep 29 '22 08:09

Ben James