search

Home  >  Q&A  >  body text

Display blobs using JavaScript

<p>I'm retrieving a Blob image from a database and I want to be able to view the image using JavaScript. The following code produces a broken image icon on the page: </p> <pre class="brush:php;toolbar:false;">var image = document.createElement('image'); image.src = 'data:image/bmp;base64,' Base64.encode(blob); document.body.appendChild(image);</pre> <p>Here is a jsFiddle that contains all the code needed, including the blob. The completed code should display the image correctly. </p>
P粉860370921P粉860370921482 days ago619

reply all(2)I'll reply

  • P粉005134685

    P粉0051346852023-08-24 14:48:24

    You can also get the BLOB object directly from XMLHttpRequest. Just set responseType to blob. This is my code:

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://localhost/image.jpg");
    xhr.responseType = "blob";
    xhr.onload = response;
    xhr.send();

    The response function is as follows:

    function response(e) {
       var urlCreator = window.URL || window.webkitURL;
       var imageUrl = urlCreator.createObjectURL(this.response);
       document.querySelector("#image").src = imageUrl;
    }

    We just create an empty image element in HTML:

    <img id="image"/>

    reply
    0
  • P粉742550377

    P粉7425503772023-08-24 00:00:37

    The problem is that I have hexadecimal data that needs to be converted to binary before Base64 encoding.

    In PHP:

    base64_encode(pack("H*", $subvalue))

    reply
    0
  • Cancelreply