CreateReadUpdateDelete : Store an image in the database
Store an image as a blob and read it from database
by SchizoDuckie
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://schizoduckie.github.io/CreateReadUpdateDelete.js/src/CRUD.js"></script>
<script src="https://schizoduckie.github.io/CreateReadUpdateDelete.js/src/CRUD.SqliteAdapter.js"></script>
<div class="well"><h1>CreateReadUpdateDelete.js BLOB Demo</h1>
<p>Store an image as a base64 string and read it from database</p>
<a href="http://pouchdb.com/2014/10/26/10-things-i-learned-from-reading-and-writing-the-pouchdb-source.html">Why no blob? Read here</a>
</div>
Load an image:
<input type="url" id="imageUrl" value="http://schizoduckie.github.io/DuckieTV/img/logo.png"><button id="loadUrl">Load</button>
<hr>
<img id="storeMe" src="http://schizoduckie.github.io/DuckieTV/img/logo.png" crossOrigin="Anonymous">
<button id="save">Save this image</button>
<hr />
<button id="read">Query all images from database</button>
<div id="images"></div>
<hr>
<button id="wipe">Wipe database</button>
CSS
#imageUrl {
width: 400px;
}
JavaScript
CRUD.DEBUG = true;
// checkout the console to see debug info by CRUD.SqliteAdapter.js
if(!'openDatabase' in window) {
alert("Your inferior browser does not support WebSQL. Try Chrome(ium), Safari, Opera, or any other Webkit based browser.");
}
function dbImage() {
CRUD.Entity.call(this);
}
CRUD.define(dbImage, {
table: 'Images',
primary: 'ID_Image',
fields: ['ID_Image', 'name', 'binaryData'],
createStatement: 'CREATE TABLE Images (ID_Image INTEGER PRIMARY KEY NOT NULL, name VARCHAR(250) NOT NULL, binaryData BLOB NULL)',
});
// initialize WebSQL database connection
CRUD.setAdapter(new CRUD.SQLiteAdapter('createreadupdatedelete_blob', {
estimatedSize: 25 * 1024 * 1024
}));
document.getElementById('loadUrl').onclick = function() {
var img = document.getElementById('storeMe');
img.src = document.getElementById('imageUrl').value;
};
document.getElementById('save').onclick = function() {
var img = document.getElementById('storeMe');
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var i = new dbImage();
i.binaryData = canvas.toDataURL("image/png");
i.name = 'DuckieTV Logo';
i.Persist().then(function() {
console.log("Image saved to database!");
});
};
document.getElementById('read').onclick = function() {
CRUD.Find('dbImage').then(function(results) {
var target = document.getElementById('images');
results.map(function(img) {
var d = document.createElement('img');
d.src = img.binaryData;
target.appendChild(d);
});
});
};
// drop tables on click and reload page
document.getElementById('wipe').onclick = function() {
CRUD.executeQuery('drop table Images').then(function() {
window.location.reload();
});
};