excel base64编码VBA不正确

qfe3c7zg  于 2023-05-01  发布在  其他
关注(0)|答案(2)|浏览(131)

我试图在VBA Excel中将JPG图像编码为Base64格式的HTML (<img src="data:image/jpg .." />)
我发现了一个类似的问题,Convert image (jpg) to base64 in Excel VBA?,并尝试了代码:

'https://stackoverflow.com/questions/2043393/convert-image-jpg-to-base64-in-excel-vba
Sub EncodeFile()

Dim strPicPath: strPicPath = "MyDriveHere:\SomePath\image.jpg" 
'Credit to Wikipedia for orange picture:    'https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Citrus_reticulata_April_2013_Nordbaden.JPG/220px-Citrus_reticulata_April_2013_Nordbaden.JPG
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
Debug.Print objDocElem.text

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

End Sub

使用这里的图像,https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Citrus_reticulata_April_2013_Nordbaden.JPG/220px-Citrus_reticulata_April_2013_Nordbaden.JPG
输出以
2ESk9uWHSmQ6ayKMjmX1FWRYG5BkERRkgK9qYbqyHKTijDQc
但它应该以
/9j/4AAQSkZJRgABAQUS ASABIAAD//g
代码的输出也没有在www. example上生成任何图像 www.example.com
为什么生成的输出提供的编码与标准Base64编码不同?

ukxgm1gy

ukxgm1gy1#

“立即”窗口没有无限的容量:如果你打印太多,你会开始失去开始。..

Debug.Print Left(objDocElem.Text, 200)

提供了预期的开始/9j/4AAQSkZJRgABAQEASABIAAD//gBgRmlsZ

lyr7nygr

lyr7nygr2#

XML对象在返回72个字符后插入换行符。参见:Base64 encode with Stream_StringToBinary inserts a newline, breaking the string?
只要去掉这个字符就可以了。..

' Get base64 value
Dim bad As String, good As String
bad = objDocElem.text
good = Replace(bad, Chr(10), "")
Debug.Print good

相关问题