You can draw the image in a canvas, encode it to base64 and then use it as a text. Almost all languages can convert between base64 and images.

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img= new Image();
img.src = "your url to image";
ctx.drawImage(img,0,0);
c.toDataURL();
//c now contains the base64 encoding of your image

the canvas can also be created dynamically and not as a part of the page. You can also wait for the onLoad event on the image.

Answer from Kristian Ivanov on Stack Overflow
Top answer
1 of 4
2

You can draw the image in a canvas, encode it to base64 and then use it as a text. Almost all languages can convert between base64 and images.

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img= new Image();
img.src = "your url to image";
ctx.drawImage(img,0,0);
c.toDataURL();
//c now contains the base64 encoding of your image

the canvas can also be created dynamically and not as a part of the page. You can also wait for the onLoad event on the image.

2 of 4
1

Use canvas..Here is the code copied from a program

function fun_nam(url,back, op){
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.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(op);
    back(dataURL);
    canvas = null; 
};
img.src = url;

}

Some details ...

The HTMLCanvasElement.toDataURL() method returns a data URI containing a representation of the image in the format specified by the type parameter (defaults to PNG). The returned image is in a resolution of 96 dpi.

Syntax: canvas.toDataURL(type, encoderOptions);

Parameters

type | Optional

  • A DOMString indicating the image format. The default type is image/png.

encoderOptions | Optional

  • A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. The default value is 0.92. Other arguments are ignored.

Return value

  • A DOMString containing the requested data URI.

Actually we are drawing the image data with the drawImage function,Then use the toDataURL function to get a base-64 encoded image data: url. The encoding should be do only after loading the full image.Else you will get some broken/grey type image after decoding.

Top answer
1 of 16
1216

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)
})
Run code snippetEdit code snippet Hide Results Copy to answer Expand

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)
  })
Run code snippetEdit code snippet Hide Results Copy to answer Expand

These approaches:

  • have better compression
  • work for other file types as well

Browser Support:

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

Tip: To convert local files, you can use live-server. Once started on the folder that contains the picture to transform, open the url in browser and using developer console you can convert the image to base 64.


2. Approach: Canvas (for legacy browsers)

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)
  }
)
Run code snippetEdit code snippet Hide Results Copy to answer Expand

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)" />
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 16
233

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

Discussions

html - How to convert an image to a string using javascript? - Stack Overflow
I would like to convert the image uploaded to the html input to a string. How can I do that using JavaScript? Thanks in advance. More on stackoverflow.com
🌐 stackoverflow.com
April 6, 2016
How to convert an image string in javascript or jquery? - Stack Overflow
I have this "little" problem... In my web app, I receive an xml message from the server that I parse with jquery. In the xml there is an element with these attributes: key and value.... More on stackoverflow.com
🌐 stackoverflow.com
html - How to turn a string of data into an image in Javascript? - Stack Overflow
The image data string has a length of 109095. The console freezes when I log this string, can't figure out why. I then try to set the src of the img in javascript like this: ... And it doesn't work. ... That's not Base64 - that is just the binary data. You need to convert it to Base64 on the ... More on stackoverflow.com
🌐 stackoverflow.com
Convert local image to base64 string in Javascript - Stack Overflow
I'm trying to convert a local image to Base64 string. I am not using any HTML and simply need javascript which references the image's path within the code. For instance, converting: C:\Users... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Tick
pqina.nl › blog › convert-an-image-to-a-base64-string-with-javascript
Convert An Image To A DataURL or Base64 String Using JavaScript - Pqina
If our image is an <img> element we can fetch the image src and convert that to a Base64 string. Alternatively we can draw the image to a canvas and then convert the canvas to an image element, this would be useful if we’re looking for a specific ...
🌐
W3docs
w3docs.com › javascript
How to Convert the Image into a Base64 String Using JavaScript | W3Docs
There are several approaches in JavaScript that can help you with converting the image into a Base64 string. Firstly, create a canvas, then load the image into it and use toDataURL() to get the Base64 representation.
Top answer
1 of 2
1

Having

<input type="file" id="picture">

You can add an event handler to it listening to the change event (this code has to come after the above HTML or be registered on the DOMContentLoaded event)

var input = document.getElementById('picture');
input.addEventListener('change', handleFiles, false);

Then your handleFiles event would draw the image into a canvas and extract the base64 string from the file:

function handleFiles(e) {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');

  var img = new Image();

  img.onload = function() {
    ctx.drawImage(img, 0, 0);

    var base64 = canvas.toDataURL();
    console.log(base64);
  }

  img.src = URL.createObjectURL(e.target.files[0]);
}

Running example bellow:

var input = document.getElementById('picture');
input.addEventListener('change', handleFiles, false);

function handleFiles(e) {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');

  var img = new Image();

  img.onload = function() {
    ctx.drawImage(img, 0, 0);

    var base64 = canvas.toDataURL();
    document.getElementById('result').value = base64;
  }

  img.src = URL.createObjectURL(e.target.files[0]);
}
textarea {
  width: 350px;
  height: 100px;
}
<input type="file" id="picture" />
<br /> <br />
<textarea id="result"></textarea>

2 of 2
1

If what you want is a dataURI version, use a FileReader and its readAsDataURL() method.

file_input.onchange = function(e) {

  var fr = new FileReader();
  fr.onload = function() {
    output.src = this.result;
  }
  fr.readAsDataURL(this.files[0]);

};
<input type="file" id="file_input" />
<img id="output" />

If you just want to display it, then you can use the URL Constructor :

file_input.onchange = function(e) {

  output.src = URL.createObjectURL(this.files[0]);

};

// don't forget to revoke the URLObject when you don't need it anymore
output.onload = function() {
  URL.revokeObjectURL(this.src);
}
<input type="file" id="file_input" />
<img id="output" />

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-convert-image-into-base64-string-using-javascript
Convert image into base64 string using JavaScript - GeeksforGeeks
February 25, 2026 - It converts binary image data into a text-based Base64 encoded string. The Base64 string can be easily stored, transmitted, or embedded directly in HTML or CSS. This can be done using the FileReader object in browsers or the Buffer class in Node.js. Here we will create a gfg.js file which will include JavaScript code and one gfg.html file.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-image-into-base64-string-using-javascript
How to convert image into base64 string using JavaScript ? | GeeksforGeeks
July 25, 2024 - 1. btoa() MethodThis method encodes a string in base-64 and uses the "A-Z", "a- ... This article explores how to convert a JavaScript Object Notation (JSON) object into a Blob object in JavaScript. Blobs represent raw data, similar to files, and can be useful for various tasks like downloading or processing JSON data. What is JSON and Blob?JSON (JavaScript Object Notation): A light ... To crop an image in JavaScript, you can use the <canvas> element to manipulate the image's dimensions and crop it to a specified area.
Find elsewhere
🌐
Delft Stack
delftstack.com › home › howto › javascript › convert an image into base64 string using javascript
How to Convert an Image Into Base64 String Using JavaScript | Delft Stack
February 2, 2024 - We will also try the file reader option to get the base64 string representation. In this case, we create a canvas element and define its dimensions - the dataURL where we will store the string representation. We will add random images from online sources, and to avoid security issues, we will ensure the object.crossOrigin = 'Anonymous'.
🌐
YouTube
youtube.com › watch
Convert Image/Blob to Base64 in JavaScript | Blob to String Made Easy! - YouTube
Want to learn how to convert/encode an image into a Base64 string using JavaScript? In this step-by-step tutorial, we’ll fetch an image, convert it into a Bl...
Published   March 19, 2025
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › FileReader › readAsDataURL
FileReader: readAsDataURL() method - Web APIs | MDN
September 18, 2025 - const preview = document.querySelector("img"); const fileInput = document.querySelector("input[type=file]"); fileInput.addEventListener("change", previewFile); function previewFile() { const file = fileInput.files[0]; const reader = new FileReader(); reader.addEventListener("load", () => { // convert image file to base64 string preview.src = reader.result; }); if (file) { reader.readAsDataURL(file); } } html ·
Top answer
1 of 2
2

If you attach an event listener to the file input, you can then recognize text once the file has been loaded successfully, like so:

<html>
<body>

<input type="file" id="myFile" name="filename">  
<br><br>

<label><b>Your Converted Text:</b></label><br><br>

<textarea cols="30" name="original" rows="10" style="width: 100%;" id="convertedText">
</textarea>

<script src='https://cdn.rawgit.com/naptha/tesseract.js/1.0.10/dist/tesseract.js'></script>

<script>  

    var myFile = document.getElementById('myFile');
    myFile.addEventListener('change', recognizeText);

    async function recognizeText({ target: { files }  }) {
        Tesseract.recognize(files[0]).then(function(result) {
            console.log("recognizeText: result.text:", result.text);
            document.getElementById("convertedText").value = result.text;
        });
    }

</script>
        
</body>
</html>
2 of 2
0

Below code will convert any image to text!

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Image to Text Converter</title>
  <script src="https://cdn.jsdelivr.net/npm/tesseract.js/dist/tesseract.min.js"></script>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      min-height: 100vh;
      background-color: #f3f4f6;
    }
    .container {
      max-width: 500px;
      width: 100%;
      padding: 20px;
      background: white;
      border-radius: 10px;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      text-align: center;
    }
    .container h1 {
      font-size: 1.5rem;
      margin-bottom: 20px;
    }
    input[type="file"] {
      margin-bottom: 20px;
    }
    #output {
      margin-top: 20px;
      padding: 10px;
      background: #f9fafb;
      border: 1px solid #e5e7eb;
      border-radius: 5px;
      overflow: auto;
      max-height: 200px;
    }
    button {
      padding: 10px 20px;
      background-color: #2563eb;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1rem;
    }
    button:hover {
      background-color: #1d4ed8;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>Image to Text Converter</h1>
    <input type="file" id="imageInput" accept="image/*">
    <button id="convertButton">Convert to Text</button>
    <div id="output" hidden>
      <h3>Extracted Text:</h3>
      <p id="text"></p>
    </div>
  </div>

  <script>
    const imageInput = document.getElementById('imageInput');
    const convertButton = document.getElementById('convertButton');
    const outputDiv = document.getElementById('output');
    const textOutput = document.getElementById('text');

    convertButton.addEventListener('click', () => {
      if (imageInput.files.length === 0) {
        alert('Please upload an image.');
        return;
      }

      const imageFile = imageInput.files[0];
      const reader = new FileReader();

      reader.onload = () => {
        Tesseract.recognize(
          reader.result, // Image data
          'eng', // Language
          {
            logger: (info) => console.log(info) // Log progress
          }
        ).then(({ data: { text } }) => {
          textOutput.textContent = text.trim();
          outputDiv.hidden = false;
        }).catch((error) => {
          console.error(error);
          alert('Error processing the image.');
        });
      };

      reader.readAsDataURL(imageFile);
    });
  </script>
</body>
</html>
🌐
xjavascript
xjavascript.com › blog › how-can-i-convert-an-image-into-base64-string-using-javascript
How to Convert Image to Base64 String Using JavaScript: Step-by-Step Guide for Server Upload — xjavascript.com
Base64 encoding converts binary data (like image files) into ASCII strings, making it easy to embed or transmit as text. This guide will walk you through converting an image to a Base64 string using JavaScript, previewing the image, and uploading it to a server.
🌐
DEV Community
dev.to › migsarnavarro › how-to-base64-encode-an-image-in-javascript-4k8e
How to base64 encode an image in javascript - DEV Community
May 1, 2020 - You will learn how you can encode an image as a base64 string in client side js, it can even be used in the browser console.
🌐
TutorialsPoint
tutorialspoint.com › converting-images-to-a-base64-data-url-using-javascript
Convert Image to Data URI with JavaScript
August 26, 2022 - Use Canvas API with toDataURL() for converting image URLs to Data URI, and FileReader API for local files. Both methods produce Base64-encoded strings that can be used directly in HTML or stored for later use.
🌐
Base64.Guru
base64.guru › home › developers › javascript › examples
Convert image to Base64 in JavaScript | Examples | JavaScript | Developers | Base64
To convert image to Base64 and get the original Base64 string, I highly recommend using one of the following methods: Encode remote file to Base64 in JavaScript · Encode form file to Base64 in JavaScript · Of course, we can use new Image() to draw a canvas and using the toDataURL() method to get the Base64 string.