/

How to Convert an Image into a Data URI String

How to Convert an Image into a Data URI String

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:

  1. Read the Image File:

    1
    const imageData = fs.readFileSync(fileLocation, 'binary');
  2. Get the Content Type:
    If you’re downloading the image from the internet, you can extract the content type from the response headers:

    1
    const contentType = response.headers['content-type'];
  3. Convert the Image Data to Base64:
    In order to generate the data URI string, you need to convert the image data into base64 format:

    1
    const base64Data = Buffer.from(imageData, 'binary').toString('base64');
  4. Create the Data URI String:
    Combine the content type and the base64 data to form the data URI string:

    1
    const dataURI = `data:${contentType};base64,${base64Data}`;

Now, you can use the dataURI inside an HTML image tag like this:

1
<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