# How to turn an image into a data URI string

> Learn how to turn an image file into a data URI string in Node.js by reading it and base64-encoding it with Buffer, then embed it directly inside an img tag.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2023-03-13 | Topics: [Node.js](https://flaviocopes.com/tags/node/) | Canonical: https://flaviocopes.com/how-to-turn-an-image-into-a-data-uri-string/

I had an image file on my filesystem and I wanted to put it inside an HTML page using the data-uri format so I could embed it into the page itself.

Here’s how I did it:

```javascript
const imageData = fs.readFileSync(fileLocation, 'binary')

const src = `data:${contentType};base64,${Buffer.from(
  imageData,
  'binary'
).toString('base64')}`
```

In my case I just download that image from the Internet, so I retrieved `contentType` from the response headers:

```javascript
const contentType = response.headers['content-type']
```

In the end I was able to use `src` inside an img tag like this: `<img src={src} />`

If you just want to drop an image file and copy the data URI without writing that script, I built a free [Base64 image encoder](https://flaviocopes.com/tools/base64-image/) that runs in your browser.
