Introduction
I had a request to update a jQuery plugin (dooScrib) so that you can get a Base64 string
for the image created and came about with these snippets. Eventually, the plugin will get updated to include them.
Background
I am trying to move all of my personal code snippets into Gists and then I also figured I would share them as tips here.
As time progresses, you can find more here.
Using the Code
Here is the snippet to convert an image into a Base64 string
:
function convertImgToBase64(id, outputFormat){
var canvas = document.createElement(id);
var imageDataURL = canvas.toDataURL(outputFormat || 'image/png');
return imageDataURL;
}
With that snippet developed, I just knew that a request would come along to reverse the process. The following snippet will take a Base64 string
and convert it back into an image:
function convertBase64toImage(id, image64) {
var canvas = document.createElement(id);
var context = canvas.getContext('2d');
var baseImage = new Image();
baseImage.onload() = function() {
context.drawImage(baseImage, 0, 0);
};
baseImage.src = image64;
}
Conclusion
Happy coding!!!
History
- 20-Jun-2014 - Initial release