PHP: recreate and display an image from binary data

PHPServer Side ProgrammingProgramming

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


   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.

Published on 07-Apr-2020 15:16:16