ASP圖片格式與base64數據相互轉換的方法,常常用於處理表單中存儲有base64字符串格式的圖片。node
<% Subfolder=year(now)&month(now)&day(now)&hour(now)&minute(now)&second(now()) ''生成當天的子文件夾的名稱 picture=Trim(request.Form("urls")) picture=replace(picture,"data:image/png;base64,","") path=Subfolder&".jpg" xmlstr="<data>"&picture&"</data>" Dim xml : Set xml=Server.CreateObject("MSXML2.DOMDocument") Dim stm : Set stm=Server.CreateObject("ADODB.Stream") xml.resolveExternals=False xml.loadxml(xmlstr) xml.documentElement.setAttribute "xmlns:dt","urn:schemas-microsoft-com:datatypes" xml.documentElement.dataType = "bin.base64" stm.Type=1 'adTypeBinary stm.Open stm.Write xml.documentElement.nodeTypedValue stm.SaveToFile Server.MapPath(path) stm.Close Set xml=Nothing Set stm=Nothing response.Write("http://codeo.cn/"&path) %>
<% Function ImagesToBase64(FileName) Dim xml Dim root Dim fs Dim FilePath Dim objStream Dim objXMLDoc Dim Base64 ''定義變量完結 '建立對像 FilePath=Server.MapPath(FileName) getFileExt = Mid(FilePath, InstrRev(FilePath, ".") + 1) Set objXMLDoc=Server.CreateObject("msxml2.FreeThreadedDOMDocument") '設定生成XML文檔的根爲 Base64Data objXMLDoc.loadXML "<?xml version='1.0'?><Base64Data />" Set fs = Server.createObject("Scripting.FileSystemObject") ''服務器須要FSO組件 If fs.FileExists(FilePath) Then '判斷File文件是否存在 '用 stream 來讀取數據 Set objStream = Server.CreateObject("ADODB.Stream") objStream.Type = 1 objStream.Open objStream.LoadFromFile FilePath objXMLDoc.documentElement.dataType = "bin.base64" objXMLDoc.documentElement.nodeTypedvalue = objStream.Read '數據流讀取結束.獲得了值 objXMLDoc '建立XML文件 Set xml = Server.CreateObject("msxml2.FreeThreadedDOMDocument") xml.load objXMLDoc If xml.ReadyState>2 Then Set root=xml.getElementsByTagName("Base64Data") Base64="" else Base64="" End If Set xml=Nothing Set objStream=Nothing else Base64="" End If Set fs=Nothing Set objXMLDoc=Nothing ImagesToBase64=Base64 End Function %> <% '測試時同文件夾應該包含該圖片文件。 response.Write ImagesToBase64("12.jpg") %>