Skip to content

Instantly share code, notes, and snippets.

@wastemobile
Last active August 29, 2015 14:04
Show Gist options
  • Save wastemobile/bf431aad477fc5ca55b0 to your computer and use it in GitHub Desktop.
Save wastemobile/bf431aad477fc5ca55b0 to your computer and use it in GitHub Desktop.
Convert image to JSON Base64 and POST to a REST API
/**
* Converts an SVG element to an IMG element with the same dimensions
* and same visual content. The IMG src will be a base64-encoded image.
* Works in Webkit and Firefox (not IE).
*/
$.fn.toImage = function() {
$(this).each(function() {
var svg$ = $(this);
var width = svg$.width();
var height = svg$.height();
// Create a blob from the SVG data
var svgData = new XMLSerializer().serializeToString(this);
var blob = new Blob([svgData], { type: "image/svg+xml;charset=utf-8" });
// Get the blob's URL
var domUrl = self.URL || self.webkitURL || self;
var blobUrl = domUrl.createObjectURL(blob);
// Load the blob into a temporary image
$('<img />')
.width(width)
.height(height)
.on('load', function() {
try {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
// Start with white background (optional; transparent otherwise)
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, width, height);
// Draw SVG image on canvas
ctx.drawImage(this, 0, 0);
// Replace SVG tag with the canvas' image
svg$.replaceWith($('<img />').attr({
src: canvas.toDataURL(),
width: width,
height: height
}));
} finally {
domUrl.revokeObjectURL(blobUrl);
}
})
.attr('src', blobUrl);
});
};
var imgElem = document.getElementById('img');
$('#urlText').keyup(function(){
$('#img').attr('src',$('#urlText').val());
});
$('#sendData').click(function(){
var imgData = JSON.stringify(getBase64Image(imgElem));
$.ajax({
url: 'http://url.com/rest/api',
dataType: 'json',
data: imgData,
type: 'POST',
success: function(data) {
console.log(data);
}
});
});
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,/, "");
}
/**
* Converts an SVG element to an IMG element with the same dimensions
* and same visual content. The IMG src will have a temporary blob URL.
* Works in Webkit and Firefox and IE10+.
*/
$.fn.toImage = function() {
$(this).each(function() {
var svg$ = $(this);
var width = svg$.width();
var height = svg$.height();
// Create a blob from the SVG data
var svgData = new XMLSerializer().serializeToString(this);
var blob = new Blob([svgData], { type: "image/svg+xml;charset=utf-8" });
// Get the blob's URL
var blobUrl = (self.URL || self.webkitURL || self).createObjectURL(blob);
// Load the blob into an image
$('<img />')
.width(width)
.height(height)
.on('load', function() {
// Overwrite the SVG tag with the img tag
svg$.replaceWith(this);
})
.attr('src', blobUrl);
});
};
@wastemobile
Copy link
Author

<input id="urlText" />
<input id="sendData" type="submit" />
<img id="img" src="http://fiddle.jshell.net/img/logo.png" />

@wastemobile
Copy link
Author

$('svg').toImage();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment