0

What I'm trying to do is encode a gif file, to include in an XML document. This is what I have now, but it doesn't seem to work.

Function gifToBase64(strGifFilename)
 On Error Resume Next
 Dim strBase64
 Set inputStream = WScript.CreateObject("ADODB.Stream")
 inputStream.LoadFromFile strGifFilename
 strBase64 = inputStream.Text
 Set inputStream = Nothing
 gifToBase64 = strBase64
End Function

3 Answers3

3

I recently wrote a post about this very subject for implementations in JScript and VBScript. Here is the solution I have for VBScript:

Public Function convertImageToBase64(filePath)
  Dim inputStream
  Set inputStream = CreateObject("ADODB.Stream")
  inputStream.Open
  inputStream.Type = 1  ' adTypeBinary
  inputStream.LoadFromFile filePath
  Dim bytes: bytes = inputStream.Read
  Dim dom: Set dom = CreateObject("Microsoft.XMLDOM")
  Dim elem: Set elem = dom.createElement("tmp")
  elem.dataType = "bin.base64"
  elem.nodeTypedValue = bytes
  convertImageToBase64 = "data:image/png;base64," & Replace(elem.text, vbLf, "")
End Function
Chris West
  • 885
  • 8
  • 17
1

Take a look here: Base64 Encode & Decode Files with VBScript. This example relies on the free XBase64 component and merely provides a wrapper for file handling.

You can also go for a pure VBScript implementation, but here you have to care for the file handling yourself. Should not be too difficult, but encoding performance will be not as good. For a few small image files it will be enough, though.

Google will turn up more.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Those look good, but I'm not able to use either due to the reliance on external dlls. What I'm looking for is to do this all in vbscript. The pure VBScript implementation relies on a ScptUtl.dll. –  Oct 09 '08 at 19:47
  • Ah, that one works, I didn't see that link on the page. Thanks Tomalak. –  Oct 09 '08 at 20:00
1

In your comment to Tomalak you state you don't want to use external dlls but in your attempted example you try to use ADODB. I suspect therefore what you mean is you don't want to install dlls that aren't natively present on a vanilia windows platform.

If that is so then MSXML may be your answer:-

Function Base64Encode(rabyt)

    Dim dom: Set dom = CreateObject("MSXML2.DOMDocument.3.0")
    Dim elem: Set elem = dom.appendChild(dom.createElement("root"))
    elem.dataType = "bin.base64"
    elem.nodeTypedValue = rabyt

    Base64Encode = elem.Text

End Function
AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306