Store Image in Local Storage
by tonejac
HTML
<form enctype="multipart/form-data">
<label for="image-upload">Select an image:</label><br/>
<input name="image-upload" type="file" class="file-input" />
</form>
<label>This is the Image:</label><br/>
<div class="image-container">
<img src="" id="image-preview" />
</div>
<br/>
<br/>
<label>This is the localstorage output:</label><br/>
<div class="localstorage-output"></div>
<br/>
<br/>
<label>This is the Canvas:</label><br/>
<canvas id="canvas-element"></canvas>
CSS
label {
font-family: arial;
font-weight: bold;
}
input {
display: block;
padding: 10px 15px;
}
#image-preview,
canvas {
margin: 20px 0 0 20px;
border: 1px solid #cccccc;
}
.image-container {
width: 200px;
height: 100px;
overflow: scroll;
}
::-webkit-scrollbar {
-webkit-appearance: none;
background-color: #e8e8e8;
width: 14px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0,0,0,.5);
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
JavaScript
function storeTheImage() {
var imgCanvas = document.getElementById('canvas-element'),
imgContext = imgCanvas.getContext("2d");
var img = document.getElementById('image-preview');
// Make sure canvas is as big as the picture BUT make it half size to the file size is small enough
imgCanvas.width = (img.width/4);
imgCanvas.height = (img.height/4);
// Draw image into canvas element
imgContext.drawImage(img, 0, 0, (img.width/4), (img.height/4));
// Get canvas contents as a data URL
var imgAsDataURL = imgCanvas.toDataURL("image/png");
// Save image into localStorage
try {
window.localStorage.setItem("imageStore", imgAsDataURL);
$('.localstorage-output').html( window.localStorage.getItem('imageStore') );
}
catch (e) {
console.log("Storage failed: " + e);
}
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image-preview').attr('src', e.target.result);
storeTheImage();
}
reader.readAsDataURL(input.files[0]);
}
}
$('.file-input').on('change', function() {
readURL(this);
});