VBS:图片文件与BASE64编码互转

2023-1-13 12:07:47 [大杂烩 - PC与手机]
Function ImagesToBase64(FilePath)
Dim xml,root,objStream,objXMLDoc,Base64

Set objXMLDoc=CreateObject("msxml2.FreeThreadedDOMDocument")
  objXMLDoc.loadXML "<?xml version='1.0'?><Base64Data />"

  Set objStream = CreateObject("ADODB.Stream")
  objStream.Type = 1
  objStream.Open
  objStream.LoadFromFile FilePath

  objXMLDoc.documentElement.dataType = "bin.base64"
  objXMLDoc.documentElement.nodeTypedvalue = objStream.Read
  '创建XML文件
     Set xml = CreateObject("msxml2.FreeThreadedDOMDocument")
     xml.load objXMLDoc
     If xml.ReadyState>2 Then
      Set root=xml.getElementsByTagName("Base64Data")
      Base64=root.Item(0).Text
     else
      Base64=""
     End If
     Set xml=Nothing
  Set objStream=Nothing
Set objXMLDoc=Nothing
ImagesToBase64=Base64

End Function

Function Base64ToImages(base64,FilePath)
Dim objXMLDoc,objStream
Set objXMLDoc=CreateObject("msxml2.FreeThreadedDOMDocument")
objXMLDoc.resolveExternals=False
objXMLDoc.loadXML("<?xml version=""1.0"" encoding=""gb2312""?><data>" & base64 & "</data>") 
objXMLDoc.documentElement.setAttribute "xmlns:dt","urn:schemas-microsoft-com:datatypes"
objXMLDoc.documentElement.dataType ="bin.base64"

Set objStream = CreateObject("ADODB.Stream")
  objStream.Type = 1
  objStream.Open
  objStream.Write objXMLDoc.documentElement.nodeTypedValue
  objStream.SaveToFile FilePath
  Set objStream=Nothing
Set objXMLDoc=Nothing
End Function