JScript – Convert Image To Base64

Yesterday I was updating an HTA (HTML Application) and needed to figure out how to convert an image into a base64 code that could be used in a stylesheet. I needed this to be able to embed an image in the source code instead of referencing an actual image. For this reason I wrote the following function (with the help of this post):

function convertImageToBase64(filePath) {
  var inputStream = new ActiveXObject('ADODB.Stream');
  inputStream.Type = 1;  // adTypeBinary
  var bytes = inputStream.Read();
  var dom = new ActiveXObject('Microsoft.XMLDOM');
  var elem = dom.createElement('tmp');
  elem.dataType = 'bin.base64';
  elem.nodeTypedValue = bytes;
  var ret = 'data:image/png;base64,' + elem.text.replace(/[^A-Z\d+=\/]/gi, '');

As you can see the convertImageToBase64 function takes the file path to the image and returns the base64 encoding as a PNG (regardless of the starting image format). You can change the format to another type, but I just stuck with PNG since it is a nice format to work with. šŸ˜Ž

2 Replies to “JScript – Convert Image To Base64”

  1. Cool! This is great help on something that I have been stuck with. Thanks! I know this is a 2013 post but I have been Googling for weeks. I want to be able to read local binary file, read it and display it as Base64 with Internet Explorer. I just have two things to add:

    – I added “return” at the end of the function.
    – I found out on another forum, you may want to do this to avoid some Security Restriction Error.

    Go to Internet options — Security Tab — Select Internet and Local Intranet — click Custom Level (button ) — Miscellaneous — select enable for Access data source across domains.

    I thought that probably also want to know that I found you from here. https://www.google.com/search?q=IE+activex+read+local+file+to+base64&ie=utf-8&oe=utf-8

Leave a Reply

Your email address will not be published. Required fields are marked *