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).
Advertisement
Answer
You can do that with the image-to-base64 library.
Installation
JavaScript
x
2
1
npm i image-to-base64
2
Usage
JavaScript
1
16
16
1
const imageToBase64 = require('image-to-base64');
2
//or
3
//import imageToBase64 from 'image-to-base64/browser';
4
5
imageToBase64("path/to/file.jpg") // Path to the image
6
.then(
7
(response) => {
8
console.log(response); // "cGF0aC90by9maWxlLmpwZw=="
9
}
10
)
11
.catch(
12
(error) => {
13
console.log(error); // Logs an error if there was one
14
}
15
)
16
Displaying an image using base64
JavaScript
1
4
1
<img src="data:image/jpg;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
2
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
3
9TXL0Y4OHwAAAABJRU5ErkJggg==" />
4