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...
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.
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.
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()).
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With