Converting an image into a data URI string allows you to embed it directly into an HTML page. If you’re looking for a way to achieve this, here’s a step-by-step guide:
-
Read the Image File:
const imageData = fs.readFileSync(fileLocation, 'binary');
-
Get the Content Type: If you’re downloading the image from the internet, you can extract the content type from the response headers:
const contentType = response.headers['content-type'];
-
Convert the Image Data to Base64: In order to generate the data URI string, you need to convert the image data into base64 format:
const base64Data = Buffer.from(imageData, 'binary').toString('base64');
-
Create the Data URI String: Combine the content type and the base64 data to form the data URI string:
const dataURI = `data:${contentType};base64,${base64Data}`;
Now, you can use the dataURI
inside an HTML image tag like this:
<img src={dataURI} />
By following these steps, you can successfully convert an image into a data URI string.
tags: data URI, image conversion, HTML, base64 encoding