javascriptphpbinary-image

How can you set the source of a image tag to binary image data, Nothing I've seen is working for me


I have binary image data that php gets from the memcached, it sends it to javascript, Javascript then creates a new image and set the source to the data, the data is already in base64_encoding, as it comes from the users machine when they upload a image file to the site, I use javascript FIle_Reader to get the binary data, send it to php ,and store it in a File_Server and memcached for later use. However when retreiving the data and trying to use it to output a viewable image, I get error, I have scoured the web, but no one really has a solution for my specific problem.

function Create_Img_From_Binary($data){
    $Data=json_encode($data);
    echo "
    <script>
    function Create_Img_From_Binary(data){
      let img= document.createElement('img');
      img.src=$data;
      document.body.appendChild(img); 
        
    }
    Create_Img_From_Binary($Data);
    </script>
    ";
   
}
$fd= fopen("img.html",'r');
$data= fread($fd,filesize("img.html"));
Create_Img_From_Binary($data);




  The img.html file just contains the raw image data

Solution

  • Use the tag this way:

    <img src="data:image/gif;base64,xxxxxxxxxxxxx...">
    

    where xxxx above is image base64 image code.

    OR

    <img src="data:image/jpeg;base64, <?=base64_encode($Data)?>">
    

    here $data is your binary image

    it just solution for your question. see if its work or not.