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
I am software developer with over 20 years of professional experience. I have been employed as a software developer since the early 90′s back when Microsoft’s Windows 3.1x was gaining popularity and IBM’s OS/2 was the predominant leader in 32-bit PC based Operating Systems.
Prior to choosing this as my profession I had studied architecture and then later Electrical and Mechanical engineering in college. As a young kid growing up I always played with computers, my first computer was a TRS-80 that I would spend countless hours writing programs for, I never really thought of programming as a profession. The story goes that in my final year of college I took a C/C++ programming class and had so much fun working on the various projects that my professor told me something that changed everything.
“You know they pay people to do stuff like this for a living?” – Professor Bolman
Check out my blog
here.
My current and ever evolving projects:
jqAlert javascript alerts done right for those using jQueryUI.
DooScrib Doodle and scribble pad written in javascript for use with HTML5 Canvas.