base64编码VBA不正确

时间:2017-08-21 16:35:05

标签: excel vba excel-vba base64

我正在尝试在VBA Excel中将JPG图像编码为HTML (<img src="data:image/jpg .." />)的Base64格式。

我找到了一个类似的问题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 / 4AAQSkZJRgABAQEASABIAAD //克

代码的输出也未在https://codebeautify.org/base64-to-image-converter#

上生成任何图像

为什么生成的输出给出了与标准Base64编码不同的编码?

1 个答案:

答案 0 :(得分:3)

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

 Debug.Print Left(objDocElem.Text, 200)

给了我预期的开始/9j/4AAQSkZJRgABAQEASABIAAD//gBgRmlsZ