d
Amit DhamuSoftware Engineer
 

Encode image as base64 using fetch

1 minute read 00000 views

Function

const encodeImageAsBase64 = async url => {
  const image = await fetch(url)
  const contentType = image.headers.get('Content-type')
  const imageBuffer = await image.arrayBuffer()

  return `data:${contentType};base64,${Buffer.from(imageBuffer).toString(
    'base64'
  )}`
}

Usage

;(async () => {
  const encoded = await encodeImageAsBase64(
    'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'
  )

  console.log(encoded)
})()