Developing on Staxmanade

How to Download and Convert an Image to Base64 Data Url

(Comments)

Today I was playing around with a side-oss-project and had the desire to take an image from the web and base64 data encode it. While I'm sure there is a ton written out there, I didn't immediately find the specific steps in a snippet of code. (Also, I can't say I looked very hard).

So what does any programmer do when he's not satisfied with what he can't find? He writes his own. Now that I've put it together I'm just going to post this here so I can find it again down the road when I need to. :)

Below is a utility function that I threw together that will take an imageUrl parameter and will return through a Promise a base64 encoded image data string. You can see from the example usage below that we're just setting an HTML image .src property to the result of this function and it should just work.

NOTE: also if you look at the code that accomplish this below, it may look a bit like "futuristic" JavaScript right now. With all the async/await, arrow functions, http fetch and all, but the cool thing is you should be able to just copy/paste the below into a JSBin/Plnkr/Codepen without issue (in Chrome). No need for Babel/TypeScript/transpiler if you're just prototyping something (as I was). Don't rely on this to work in all browsers yet but I'm sure when I'll be googling myself for this snippet in the future, this should work in most browsers so I'll just leave this here for now.

async function getBase64ImageFromUrl(imageUrl) {
  var res = await fetch(imageUrl);
  var blob = await res.blob();

  return new Promise((resolve, reject) => {
    var reader  = new FileReader();
    reader.addEventListener("load", function () {
        resolve(reader.result);
    }, false);

    reader.onerror = () => {
      return reject(this);
    };
    reader.readAsDataURL(blob);
  })
}

An example usage of the above:

getBase64ImageFromUrl('http://approvaltests.com/images/logo.png')
    .then(result => testImage.src = result)
    .catch(err => console.error(err));

As an alternative to base64 encoded FileReader approach above, you can also also use the URL.createObjectURL return URL.createObjectURL(blob);

There's of course a number of online tools that do this for you already.

Hope this helps future me find the implementation a min or two faster some day.

Happy Encoding!

Comments