Skip to content

Instantly share code, notes, and snippets.

@fuzzyfox
Created October 14, 2013 11:00
Show Gist options
  • Save fuzzyfox/6973988 to your computer and use it in GitHub Desktop.
Save fuzzyfox/6973988 to your computer and use it in GitHub Desktop.
JavaScript: image to dataurl converter similar to http://daturi.me/ but clientside conversion
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image 2 DataURL</title>
<style>
#images {
width: 420px;
margin: auto;
}
#images img {
max-width: 420px;
max-height: 640px;
}
</style>
</head>
<body>
<form action="#">
<!-- capture=camera allows user to take photos if on phone/tablet -->
<input id="inputImage" type="file" accept="image/*;capture=camera">
<!-- Preview image hidden as we only need it to redraw into the canvas for conversion. -->
<img src="about:blank" alt="" id="outputImage" style="display:none;">
</form>
<div id="images"></div>
<script>
(function(window, document, undefined){
var inputImage = document.querySelector('#inputImage'),
outputImage = document.querySelector('#outputImage'),
// takes an image and converts it to a data url via the canvas
img2dataurl = function(img){
var imgCanvas = document.createElement('canvas'),
imgContext = imgCanvas.getContext('2d');
imgCanvas.width = img.width;
imgCanvas.height = img.height;
imgContext.drawImage(img, 0, 0, img.width, img.height);
var dataImage = document.createElement('img');
dataImage.src = imgCanvas.toDataURL('image/png');
// display images w/ dataurl
document.querySelector('#images').appendChild(dataImage);
var pre = document.createElement('input');
pre.value = imgCanvas.toDataURL('image/png');
document.querySelector('#images').appendChild(pre);
document.querySelector('#images').appendChild(document.createElement('hr'));
}
// loads an image localy and displays it on input change.
if(inputImage && outputImage){
inputImage.onchange = function(event){
var files = event.target.files,
file;
if(files && files.length > 0){
file = files[0];
try {
var URL = window.URL || window.webkitURL,
imgURL = URL.createObjectURL(file);
outputImage.src = imgURL;
URL.revokeObjectURL(imgURL);
setTimeout(function(){
img2dataurl(outputImage);
}, 100);
}
catch(e){
try{
var fileReader = new FileReader();
fileReader.onload = function(event){
outputImage.src = event.target.result;
setTimeout(function(){
img2dataurl(outputImage);
}, 100);
};
fileReader.readAsDataURL(file);
}
catch(e){
console.log("Neither createObjectURL or FileReader are supported");
}
}
}
}
}
})(this, this.document);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment