0

How to create a function which gets the exact image file from the server and then converting it to base 64 and lastly storing it to a variable.

Note: Exact image file (no need to loop through the directory to list all files).

1 Answer 1

1

You can do that with the image-to-base64 library.

Installation

npm i image-to-base64

Usage

const imageToBase64 = require('image-to-base64');
//or
//import imageToBase64 from 'image-to-base64/browser';

imageToBase64("path/to/file.jpg") // Path to the image
    .then(
        (response) => {
            console.log(response); // "cGF0aC90by9maWxlLmpwZw=="
        }
    )
    .catch(
        (error) => {
            console.log(error); // Logs an error if there was one
        }
    )

Displaying an image using base64

<img src="data:image/jpg;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
    AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
        9TXL0Y4OHwAAAABJRU5ErkJggg==" />
Sign up to request clarification or add additional context in comments.

2 Comments

Tried this, but all it does was transform the path of the image to base64 and not the image itself.
seems to be transforming the image to base64 when I try it. I added img tag usage in my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.