Image to base64 converter

Image to base64 converter

by Pavlo

HTML

<input id="imgSrcInput" placeholder="enter image src"/>
<br/>
<input id="imgBase64Input" disabled/>
<br/>
<img id="imgWithBase64"/>

JavaScript

function getImageBase64(imgSrc, width, height) {
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    var context = canvas.getContext("2d");
    var deferred = $.Deferred();
    //$('<img src="'+ imgSrc +'">')
    var timestamp = new Date().getTime();
    $("<img/>").attr("src", imgSrc + "&" + timestamp)
    .attr('crossOrigin', 'anonymous')
    .load(function() {
    		if(width && height) {
        	context.scale(width/this.width,  height/this.height);
        }
        context.drawImage(this, 0, 0); 
        deferred.resolve(canvas.toDataURL());               
    });
    return deferred.promise();    
}
$("#imgSrcInput").val("//www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
getImageBase64($("#imgSrcInput").val(), 36, 36).then(function(sBase64){
	$('#imgBase64Input').val(sBase64);
  $('body').append('<img src="'+sBase64+'"/>');
})