Convert hex string (image) to base64 (for browser rendering) in VBScript

后端 未结 2 843
没有蜡笔的小新
没有蜡笔的小新 2021-01-07 11:52

I have a script that outputs a .bmp captcha image.

The image is built in hexadecimal, and converted to binary and sent to the browser via response.binaryWrite

2条回答
  •  一整个雨季
    2021-01-07 12:09

    The Microsoft.XMLDOM has built in converters for bin.base64 and bin.hex. I wrote functions that demonstrate how to use this:

    Function TextToBinary(text, dataType)
      Dim dom
      Set dom = CreateObject("Microsoft.XMLDOM")
      dom.loadXML("")
      dom.documentElement.nodeTypedValue = text
      dom.documentElement.dataType = dataType
      TextToBinary = dom.documentElement.nodeTypedValue
    End Function
    
    Function BinaryToText(binary, dataType)
      Dim dom
      Set dom = CreateObject("Microsoft.XMLDOM")
      dom.loadXML("")
      dom.documentElement.dataType = dataType
      dom.documentElement.nodeTypedValue = binary
      dom.documentElement.removeAttribute("dt:dt")
      BinaryToText = dom.documentElement.nodeTypedValue
    End Function
    
    Function HexToBase64(strHex)
      HexToBase64 = BinaryToText(TextToBinary(strHex, "bin.hex"), "bin.base64")
    End Function
    
    Function Base64ToHex(strBase64)
      Base64ToHex = BinaryToText(TextToBinary(strBase64, "bin.base64"), "bin.hex")
    End Function
    

    Here's an example of their usage:

    MsgBox HexToBase64("41")
    MsgBox Base64ToHex("QQ==")
    

    Also look at the ADODB.Stream as a means of working with binary files. It'll work with these routines.

提交回复
热议问题