Python 和 VBScript 对文件编码-解码的方式 (Hex, Base64) 的疑问

来源:互联网 发布:mac电脑远程控制怎么弄 编辑:程序博客网 时间:2024/06/06 21:42

本人目前的项目需要在Windows上用VBScript将一文件转换为二进制码存入数据库,再在Linux上用Python从数据库中读取并解码成图片。反复调试,发现微软和Python的转码标准不统一,导致了这种实现方式失败。若有哪位大侠是这方面的高手还请不吝赐教


1. Windows上使用VBScript对图片转码为“base64”格式:

Function ReadBinary(FileName)Const adTypeBinary = 1Dim stream, xmldom, nodeSet xmldom = CreateObject("Microsoft.XMLDOM")Set node = xmldom.CreateElement("binary")node.DataType = "bin.base64"Set stream = CreateObject("ADODB.Stream")stream.Type = adTypeBinarystream.Openstream.LoadFromFile FileNamenode.NodeTypedValue = stream.Readstream.CloseSet stream = NothingReadBinary = node.TextSet node = NothingSet xmldom = NothingEnd FunctionPublic 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 = NothingEnd FunctionhexVal = ReadBinary("c:\desk_2.png")Call WriteFile_Append("c:\ttt.txt", hexVal)

2. 用Python读取文件,并转换回图片格式:

f = open('c:\\ttt.txt')img = f.read()f.close()f1 = open('c:\\desk.png', 'a+')f1.write(img.decode('base64'))f1.close()

3. 发现原图desk_2.png和转换完后的图desk.png大小相差1k,但是desk.png无法显示出图片。


注:

1. 用一个小一点的gif试了一下,转换后图片缺失部分像素

2. VBS和Python同时使用“hex”代替“base64”,中间编码的格式更是大相径庭


看来MS和Python对于格式转换的标准不一样...若有哪位大侠是这方面的高手还请不吝赐教,谢谢


---------- 以下于2012年5月17日 ------

注:此问题已解决,之前是因为python的“open”使用了“a+”方式打开文件,经查此方法无法写入二进制文件,只需要将其改为“wb”,一切搞定