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.Open();
inputStream.Type = 1; // adTypeBinary
inputStream.LoadFromFile(filePath);
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. 😎
3 Comments
Dino · June 26, 2015 at 8:07 PM
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.
https://community.qlik.com/thread/32558#thread-message-186576
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
Programmer · August 12, 2015 at 8:17 AM
Thanks Chris, it was helpful!
paweł · November 24, 2017 at 8:20 AM
but how to decode BASE64 string to binary and save to .gif