How to convert 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 js file for this... ? Else how to convert it



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).


There are multiple approaches you can choose from:

1. Approach: FileReader

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

function toDataURL(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
  };'GET', url);
  xhr.responseType = 'blob';

toDataURL('', 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

  .then(dataUrl => {
    console.log('RESULT:', dataUrl)

These approaches:

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

Browser Support:

2. Approach: Canvas

Load the image into an Image-Object, paint it to a non tainted 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);
  img.src = src;
  if (img.complete || img.complete === undefined) {
    img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
    img.src = src;

  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:

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)
<input type="file" onchange="encodeImageFileAsURL(this)" />


This snippet can convert your string, image and even video file to Base64 string data.

<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type='text/javascript'>
  function encodeImageFileAsURL() {

    var filesSelected = document.getElementById("inputFileToLoad").files;
    if (filesSelected.length > 0) {
      var fileToLoad = filesSelected[0];

      var fileReader = new FileReader();

      fileReader.onload = function(fileLoadedEvent) {
        var srcData =; // <--- data: base64

        var newImage = document.createElement('img');
        newImage.src = srcData;

        document.getElementById("imgTest").innerHTML = newImage.outerHTML;
        alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
        console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);


Basically, if your image is

<img id='Img1' src='someurl'>

then you can convert it like

var c = document.createElement('canvas');
var img = document.getElementById('Img1');
c.height = img.naturalHeight;
c.width = img.naturalWidth;
var ctx = c.getContext('2d');

ctx.drawImage(img, 0, 0, c.width, c.height);
var base64String = c.toDataURL();

Here is what i did

//Author James Harrington 2014
function base64(file, callback){
  var coolFile = {};
  function readerOnload(e){
    var base64 = btoa(;
    coolFile.base64 = base64;

  var reader = new FileReader();
  reader.onload = readerOnload;

  var file = file[0].files[0];
  coolFile.filetype = file.type;
  coolFile.size = file.size;
  coolFile.filename =;

And here is how you use it

base64( $('input[type="file"]'), function(data){

I found that the most safe and reliable way to do it is to use FileReader()

Demo: Image to Base64

<!DOCTYPE html>
    <meta charset="UTF-8">
    <input id="myinput" type="file" onchange="encode();" />
    <div id="dummy">
      <textarea style="width:100%;height:500px;" id="txt">
      function encode() {
        var selectedfile = document.getElementById("myinput").files;
        if (selectedfile.length > 0) {
          var imageFile = selectedfile[0];
          var fileReader = new FileReader();
          fileReader.onload = function(fileLoadedEvent) {
            var srcData =;
            var newImage = document.createElement('img');
            newImage.src = srcData;
            document.getElementById("dummy").innerHTML = newImage.outerHTML;
            document.getElementById("txt").value = document.getElementById("dummy").innerHTML;

You could use FileAPI, but it's pretty much unsupported.


If you have a file object this simple function will work:-

function getBase64 (file,callback) {

    const reader = new FileReader();

    reader.addEventListener('load', () => callback(reader.result));


Usage Ex:-

getBase64(fileObjectFromInput, function(base64Data){
    console.log("base 64 of file is",base64Data);//here you can have your code which uses base64 for its operation,//file to base64 by oneshubh

As far as i know image can be converted into base64 string either by FileReader() or storing it in canvas element and then use toDataURL() to get image.I had the simmilar kind of problem you can refer this.

Convert an image to canvas that is already loaded


Try This code

File upload Chnage event ccall this function

  $("#fileproof").on('change', function () {
                readImage($(this)).done(function (base64Data) { $('#<%=hfimgbs64.ClientID%>').val(base64Data); });

function readImage(inputElement) {
    var deferred = $.Deferred();

    var files = inputElement.get(0).files;

    if (files && files[0]) {
        var fr = new FileReader();
        fr.onload = function (e) {
    } else {

    return deferred.promise();

Store base64data in hidden filed to use.


            let file =[0];
            let reader = new FileReader();  
            reader.onloadend = function() {
                console.log('RESULT', reader.result)

Well, if you are using dojo, it gives us direct way to encode or decode into base64.

Try this:

To encode an array of bytes using dojox.encoding.base64:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a base64-encoded string:

var bytes = dojox.encoding.base64.decode(str);


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.