PHP: recreate and display an image from binary data


This can be done using data URI in the image src attribute.

Format

data:[<MIME-type>][;charset="<encoding>"][;base64],<data>
<?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('some_image.png','image/png'); ?>" alt="Image sample" />

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.

Updated on: 07-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements