2

I have an image url:

url = "https://wallpaperaccess.com/full/3678503.png";

Is there any way to get base64 encoded string of that remote file in javascript?

annesha
  • 21
  • 2
  • 1
    The answer to the question in the title is no. Though you can load and show an image, you can't modify it with JS if the image wasn't loaded with proper CORS headers. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image – Teemu Apr 12 '22 at 05:35
  • Why do you want to do this? Certainly there are better ways to do the same. – Kaiido Apr 12 '22 at 06:02

1 Answers1

1

I found on SO this codesnipet to achieve this. The only problem would be that you will run into CORS Problem. If you are the owner of the page which hosted the image you can configure up to avoid CORS.

const toDataURL = url => fetch(url)
  .then(response => response.blob())
  .then(blob => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onloadend = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(blob)
  }))


toDataURL('https://wallpaperaccess.com/full/3678503.png')
  .then(dataUrl => {
    console.log('RESULT:', dataUrl)
  })

And here the Link where i found the source: https://stackoverflow.com/a/20285053/14807111

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79