Convert image to JSON Base64 and POST to a REST API
Convert image to JSON Base64 and POST to a REST API
by crowjonah
HTML
<input id="urlText"...
JavaScript
var tb = $('body'),
imgElem = document.getElementById('img');
$('#img').attr('src',$('#urlText').val());
$('#urlText').keyup(function(){
$('#img').attr('src',$('#urlText').val());
});
$('#sendData').click(function(){
var imgData = JSON.stringify(getBase64Image(imgElem));
$.ajax({
url: 'https://api.imgur.com/3/image',
headers: {"Authorization": "Client-ID 53fe12e8baec87f"},
dataType: 'json',
data: imgData,
type: 'POST',
success: function(data) {
console.log(data);
console.log(data.data.link);
if (data && data.data && data.data.link)
{
newLink(data.data.link);
}
}
});
});
function newLink(ref) {
var fburl = 'http://www.facebook.com/sharer.php?s=100&p[title]='+encodeURIComponent('Special Image') + '&p[summary]=' + encodeURIComponent('Special Image Description') + '&p[url]=' + encodeURIComponent('http://www.nike.com') + '&p[images][0]=' + encodeURIComponent(ref);
var nl = $('<div><a href="' + ref + '">' + ref + '</a><a href="' + fburl + '>FB Share</a></div>');
tb.append(nl);
}
function getBase64Image(imgElem) {
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18"
var canvas = document.createElement("canvas");
canvas.width = imgElem.clientWidth;
canvas.height = imgElem.clientHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgElem, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}