Skip to content

Display an image stored in a BLOB in a browser

Doctor Who edited this page Jan 26, 2023 · 2 revisions

Suppose you have a database stored in the variable db, containing a table images with the following contents:

id (INTEGER) image (BLOB)
1 image stored as BLOB

You want to display the image, either on a canvas, or directly as an image element on your page.

//[...]
var stmt = db.prepare("SELECT image FROM test WHERE id=$id"); // SQL statement
var uarray = stmt.getAsObject({$id:1})['image']; // UInt8Array containing the bytes of the image
// (of course you can use other API methods to query your database
stmt.free(); // Free the memory used by the statement

// The tricky part : create a blob url to your image, that you can use anywhere
var objurl = window.URL.createObjectURL(new Blob([uarray]));
var img = new Image();
img.src = objurl;
img.onload = function() {
  // do something with your image
}