Convert local image to base64 javascript

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\Work\Desktop\TestImage.jpg

into

/9j/4AAQSkZJRgABAQEASABIAAD/4QBKRXhpZgAASUkqAAgAAAADABoBBQABAAAAMgAAABsBBQABAAAAOgAAACgBAwABAAAAAgAAAAAAAAAAVOoqgJaYAABU6iqAlpgA/+IMWElDQ19QUk9GSUxFAAEBAAAMSExpbm8CEAAAbW50clJHQiBYWVogB84AAgAJAAYAMQAAYWNzcE1TRlQAAAAASUVDIH.....etc...

There are many posts like this but they all seem to utilize HTML in some way, in order to identify the file path. I'm hoping I can write a defined filepath within the javascript.

I tried this to no avail:

function convertImgToBase64()
{
    var canvas = document.createElement('CANVAS');
    img = document.createElement('img'),
    img.src = C:\Users\Work\Desktop\TestImage.jpg;
    img.onload = function()
    {
        canvas.height = img.height;
        canvas.width = img.width;
        var dataURL = canvas.toDataURL('image/png');
        alert(dataURL);
        canvas = null; 
    };
}

One example has the following html and javascript, but I'm hoping this can be consolidated together. Thanks for your support

HTML:






JS Bin






Javascript:

function el(id){return document.getElementById(id);} // Get elem by ID

function readImage() {
    if ( this.files && this.files[0] ) {
        var FR= new FileReader();
        FR.onload = function(e) {
             el("img").src = e.target.result;
             el("base").innerHTML = e.target.result;
        };       
        FR.readAsDataURL( this.files[0] );
    }
}

el("asd").addEventListener("change", readImage, false);\

Its demo found here

In this short tutorial we explore 3 different JavaScript methods to convert an image into a Base64 string. We look at converting a File object or Blob, a canvas element, and an image tag.

In all examples below we assume we already have a , , File, or Blob object available.

We’ll be converting images to DataURLs, we can use the function below to convert a DataURL to a Base64 string.

const getBase64StringFromDataURL = (dataURL) =>
    dataURL.replace('data:', '').replace(/^.+,/, '');

Let’s get started.

Image is a File object or Blob

When the image is a File object or Blob we can use the FileReader API please see this article on converting a file to base64 string or dataURL.

We’ll also use the FileReader API when converting an image tag to a Base64 string.

Image is a Canvas element

If we have a that we want to turn into a Base64 string we can use toDataURL on the Canvas element.

<canvas width="300" height="150" id="my-canvas">canvas>

<script>
    const canvas = document.getElementById('my-canvas');

    // Convert canvas to dataURL and log to console
    const dataURL = canvas.toDataURL();
    console.log(dataURL);
    // Logs data:image/png;base64,wL2dvYWwgbW9yZ...

    // Convert to Base64 string
    const base64 = getBase64StringFromDataURL(dataURL);
    console.log(base64);
    // Logs wL2dvYWwgbW9yZ...
script>

By default the canvas outputs to a lossless PNG, we can pass 'image/png', 'image/jpeg' or 'image/webp' to the toDataURL method to get a different format.

When using 'image/jpeg' or 'image/webp' we can pass the image compression as the last argument, 0 means a lot of compression, 1 means no compression.

<canvas width="300" height="150" id="my-canvas">canvas>

<script>
    const canvas = document.getElementById('my-canvas');

    // Convert canvas to dataURL and log to console
    const dataURL = canvas.toDataURL('image/jpeg', 0.5);
    console.log(dataURL);
    // Logs data:image/jpeg;base64,wL2dvYWwgbW9yZ...

    // Convert to Base64 string
    const base64 = getBase64StringFromDataURL(dataURL);
    console.log(base64);
    // Logs wL2dvYWwgbW9yZ...
script>

Image is an img element

If our image is an 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 image format.

If the image is located on a remote server the CORS configuration of the remote server must allow our local script to access the image.

Fetching the image source

Note that the MIME type returned by remote server in the Content-Type response header is reflected in the DataURL.

If the MIME type is incorrect the DataURL will be incorrect as well.

<img src="my-image.jpeg" id="my-image" />

<script>
    const image = document.getElementById('my-image');

    // Get the remote image as a Blob with the fetch API
    fetch(image.src)
        .then((res) => res.blob())
        .then((blob) => {
            // Read the Blob as DataURL using the FileReader API
            const reader = new FileReader();
            reader.onloadend = () => {
                console.log(reader.result);
                // Logs data:image/jpeg;base64,wL2dvYWwgbW9yZ...

                // Convert to Base64 string
                const base64 = getBase64StringFromDataURL(reader.result);
                console.log(base64);
                // Logs wL2dvYWwgbW9yZ...
            };
            reader.readAsDataURL(blob);
        });
script>

Drawing the image to a canvas

Drawing the image to a canvas first allows us to convert it to a different format.

Please note that this approach is slower than simply fetching the image src as shown in the previous example.

An additional caveat is that the canvas element has a maximum size, for some browsers this size limit is very low causing problems when converting the image.

<img src="my-image.jpeg" id="my-image" />

<script>
    const image = document.getElementById('my-image');

    const toDataURL = () => {
        const canvas = document.createElement('canvas');

        // We use naturalWidth and naturalHeight to get the real image size vs the size at which the image is shown on the page
        canvas.width = image.naturalWidth;
        canvas.height = image.naturalHeight;

        // We get the 2d drawing context and draw the image in the top left
        canvas.getContext('2d').drawImage(image, 0, 0);

        // Convert canvas to DataURL and log to console
        const dataURL = canvas.toDataURL();
        console.log(dataURL);
        // logs data:image/png;base64,wL2dvYWwgbW9yZ...

        // Convert to Base64 string
        const base64 = getBase64StringFromDataURL(dataURL);
        console.log(base64);
        // Logs wL2dvYWwgbW9yZ...
    };

    // If the image has already loaded, let's go!
    if (image.complete) toDataURL(image);
    // Wait for the image to load before converting
    else image.onload = toDataURL;
script>

Wrapping up

We converted a File, Blob, , and to DataURLs and we looked at how to convert a DataURL to a Base64 string. By looking at different methods to convert images to Base64 strings we now know the pros and cons of each approach.

How do I convert an image to Base64?

To decode an image from the Base64 Encoded string, perform the following steps..
Open the Base64 to Image Converter..
Enter a Base64 Encoded string..
Select the Image type. ... .
After selecting the Image type, click on the "Generate Image" button..
The tool decodes the Base64 Encoded string and displays the image..

Can we convert image URL to Base64?

If our image is an 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 image format.

Can you convert any file 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.

What is Base64 image?

Base64 encoding is a way to encode binary data in ASCII text. It's primarily used to store or transfer images, audio files, and other media online. It is also often used when there are limitations on the characters that can be used in a filename for various reasons.