Display blobs using JavaScript
P粉860370921
P粉860370921 2023-08-23 20:45:06
0
2
614
<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粉860370921
P粉860370921

reply all(2)
P粉005134685

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"/>
P粉742550377

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))
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template