2

I got a script which takes several images from my MySQL database, which are stored as blobs. This script is accessed from a JavaScript / Ajax request.

So for now i display the blob in a div. But how can i convert the blob to an image in JavaScript?

2
  • 1
    Have a look at this: jsfiddle.net/Jan_Miksovsky/yy7Zs Commented Apr 20, 2015 at 15:51
  • 1
    You have to serve it from the server, not send it with ajax, or if you just have to send it with ajax, use base64_encode first so it's valid Base64 when it's received. Commented Apr 20, 2015 at 15:51

1 Answer 1

3

First, you could expose the image data as resources on the server-side then instantiate an image node in your client-side with the src set the appropriate URL.

<img src="mydomain/images/my-resource.png" />

The resource mydomain/images/my-resource.png does not need to be a static resource on the server; the URL just needs to return the image data in an HTTP response.

Second, if you have the blob in base64 on the client-side already, use a data-url. Format (from Wikipedia):

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

Example (from Wikpedia):

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

If you actually have raw binary data on the client-side then the btoa function may be of use when constructing said data-url.

Finally, you could also use the HTML5 File API, performing an XMLHttpRequest, configured with a responseType of either 'blob', or 'arraybuffer'. You can then instantiate an in-memory URL for the object, and assign this to the src of an Image DOM node.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.