ASP图片格式与base64数据互转方法

ASP图片格式与base64数据相互转换的方法,经常用于处理表单中存储有base64字符串格式的图片。

获取到base64数据,转换成图片

<%
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)
%>

图片转换为Base64字符串方法

<%
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")
%>

 

posted @ 2015-11-24 15:51  Mr. Hu  阅读(5726)  评论(0编辑  收藏  举报
Map