Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an image into Base64 string using JavaScript?

I need to convert my image to a Base64 string so that I can send my image to a server.

Is there any JavaScript file for this? Else, how can I convert it?

like image 875
coderslay Avatar asked May 27 '11 09:05

coderslay


People also ask

Can we convert image to Base64?

Convert Images to Base64Just select your JPG, PNG, GIF, Webp, or BMP picture or drag & drop it in the form below, press the Convert to Base64 button, and you'll get a base-64 string of the image. Press a button – get base64. No ads, nonsense, or garbage. Drag and drop your image here!

How do I convert to Base64?

Convert Files to Base64 Just select your file or drag & drop it below, press the Convert to Base64 button, and you'll get a base64 string. Press a button – get base64. No ads, nonsense, or garbage. The input file can also be an mp3 or mp4.


2 Answers

There are multiple approaches you can choose from:

1. Approach: FileReader

Load the image as blob via XMLHttpRequest and use the FileReader API (readAsDataURL()) to convert it to a dataURL:

function toDataURL(url, callback) {   var xhr = new XMLHttpRequest();   xhr.onload = function() {     var reader = new FileReader();     reader.onloadend = function() {       callback(reader.result);     }     reader.readAsDataURL(xhr.response);   };   xhr.open('GET', url);   xhr.responseType = 'blob';   xhr.send(); }  toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {   console.log('RESULT:', dataUrl) })

This code example could also be implemented using the WHATWG fetch API:

const toDataURL = url => fetch(url)   .then(response => response.blob())   .then(blob => new Promise((resolve, reject) => {     const reader = new FileReader()     reader.onloadend = () => resolve(reader.result)     reader.onerror = reject     reader.readAsDataURL(blob)   }))   toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0')   .then(dataUrl => {     console.log('RESULT:', dataUrl)   })

These approaches:

  • lack in browser support
  • have better compression
  • work for other file types as well

Browser Support:

  • http://caniuse.com/#feat=filereader
  • http://caniuse.com/#feat=fetch

2. Approach: Canvas

Load the image into an Image-Object, paint it to a nontainted canvas and convert the canvas back to a dataURL.

function toDataURL(src, callback, outputFormat) {   var img = new Image();   img.crossOrigin = 'Anonymous';   img.onload = function() {     var canvas = document.createElement('CANVAS');     var ctx = canvas.getContext('2d');     var dataURL;     canvas.height = this.naturalHeight;     canvas.width = this.naturalWidth;     ctx.drawImage(this, 0, 0);     dataURL = canvas.toDataURL(outputFormat);     callback(dataURL);   };   img.src = src;   if (img.complete || img.complete === undefined) {     img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";     img.src = src;   } }  toDataURL(   'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',   function(dataUrl) {     console.log('RESULT:', dataUrl)   } )

In detail

Supported input formats:

image/png, image/jpeg, image/jpg, image/gif, image/bmp, image/tiff, image/x-icon, image/svg+xml, image/webp, image/xxx

Supported output formats:

image/png, image/jpeg, image/webp(chrome)

Browser Support:

  • http://caniuse.com/#feat=canvas
  • Internet Explorer 10 (Internet Explorer 10 just works with same origin images)


3. Approach: Images from the local file system

If you want to convert images from the users file system you need to take a different approach. Use the FileReader API:

function encodeImageFileAsURL(element) {   var file = element.files[0];   var reader = new FileReader();   reader.onloadend = function() {     console.log('RESULT', reader.result)   }   reader.readAsDataURL(file); }
<input type="file" onchange="encodeImageFileAsURL(this)" />
like image 112
HaNdTriX Avatar answered Oct 11 '22 06:10

HaNdTriX


You can use the HTML5 <canvas> for it:

Create a canvas, load your image into it and then use toDataURL() to get the Base64 representation (actually, it's a data: URL, but it contains the Base64-encoded image).

like image 44
ThiefMaster Avatar answered Oct 11 '22 07:10

ThiefMaster