本人目前的项目需要在Windows上用VBScript将一文件转换为二进制码存入数据库,再在Linux上用Python从数据库中读取并解码成图片。反复调试,发现微软和Python的转码标准不统一,导致了这种实现方式失败。若有哪位大侠是这方面的高手还请不吝赐教
1. Windows上使用VBScript对图片转码为“base64”格式:
Function ReadBinary(FileName) Const adTypeBinary = 1 Dim stream, xmldom, node Set xmldom = CreateObject("Microsoft.XMLDOM") Set node = xmldom.CreateElement("binary") node.DataType = "bin.base64" Set stream = CreateObject("ADODB.Stream") stream.Type = adTypeBinary stream.Open stream.LoadFromFile FileName node.NodeTypedValue = stream.Read stream.Close Set stream = Nothing ReadBinary = node.Text Set node = Nothing Set xmldom = Nothing End Function Public Function WriteFile_Append(pathway,words) Dim fileSystemObj,fileSpec,logFile,way Set fileSystemObj = CreateObject("Scripting.FileSystemObject") fileSpec = pathway Set logFile = fileSystemObj.OpenTextFile(fileSpec, 8, true) logFile.WriteLine (CStr(words)) logFile.Close Set logFile = Nothing End Function hexVal = ReadBinary("c:\desk_2.png") Call WriteFile_Append("c:\ttt.txt", hexVal)
f = open('c:\\ttt.txt') img = f.read() f.close() f1 = open('c:\\desk.png', 'a+') f1.write(img.decode('base64')) f1.close()
注:
1. 用一个小一点的gif试了一下,转换后图片缺失部分像素
2. VBS和Python同时使用“hex”代替“base64”,中间编码的格式更是大相径庭
看来MS和Python对于格式转换的标准不一样...若有哪位大侠是这方面的高手还请不吝赐教,谢谢
---------- 以下于2012年5月17日 ------
注:此问题已解决,之前是因为python的“open”使用了“a+”方式打开文件,经查此方法无法写入二进制文件,只需要将其改为“wb”,一切搞定