Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Saving and Loading HTML5 Canvas Images

5.00/5 (1 vote)
20 Jun 2014MIT 8.1K  
Code for loading and saving images in an HTML5 canvas via Base64

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:

JavaScript
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:

JavaScript
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

License

This article, along with any associated source code and files, is licensed under The MIT License