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