在Excel VBA中将图像(jpg)转换为base64?

时间:2010-01-11 17:02:31

标签: xml excel vba base64

我需要将Excel中的图像(或通过VBA)转换为base64 (最后我将进行XML输出)。

我该怎么做?我是否需要引用DOM?

我一直在阅读this question,但它只适用于文字字符串而不是图片......

有没有人有我能看到的代码?

1 个答案:

答案 0 :(得分:7)

这是一个功能。不记得我从哪里得到它。

Public Function EncodeFile(strPicPath As String) As String
    Const adTypeBinary = 1          ' Binary file is encoded

    ' Variables for encoding
    Dim objXML
    Dim objDocElem

    ' Variable for reading binary picture
    Dim objStream

    ' Open data stream from picture
    Set objStream = CreateObject("ADODB.Stream")
    objStream.Type = adTypeBinary
    objStream.Open
    objStream.LoadFromFile (strPicPath)

    ' Create XML Document object and root node
    ' that will contain the data
    Set objXML = CreateObject("MSXml2.DOMDocument")
    Set objDocElem = objXML.createElement("Base64Data")
    objDocElem.dataType = "bin.base64"

    ' Set binary value
    objDocElem.nodeTypedValue = objStream.Read()

    ' Get base64 value
    EncodeFile = objDocElem.Text

    ' Clean all
    Set objXML = Nothing
    Set objDocElem = Nothing
    Set objStream = Nothing

End Function