XSLT: Convert base64 data into image files

前端 未结 4 1892
日久生厌
日久生厌 2020-12-03 02:07

I have seen several questions on how to encode an image file in base64, but how about the other way around - how do I reconstitute a picture from a base64 string stored in a

相关标签:
4条回答
  • 2020-12-03 02:46

    There is a better method available since Saxon 9.5 via the EXPath File extension module (available in Saxon-PE and Saxon-EE).

    Here is a fragment of the code I'm using to extract binary image files from Word documents (source XML is in WordProcessingML format):

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:file="http://expath.org/ns/file" xmlns:pkg="http://schemas.microsoft.com/office/2006/xmlPackage">
    
    <xsl:template match="/pkg:package">
        <xsl:apply-templates select="pkg:part/pkg:binaryData"/>
    </xsl:template>
    
    <xsl:template match="pkg:binaryData">
        <xsl:variable name="filename">
            <xsl:value-of select="replace(../@pkg:name, '/word/media/', '')"/>
        </xsl:variable>
        <xsl:variable name="path" select="concat('/some/folder/', $filename)"/>
        <xsl:message><xsl:value-of select="$path"/></xsl:message>
    
        <xsl:value-of select="file:write-binary($path, xs:base64Binary(string()))"/>       
    </xsl:template>
    
    0 讨论(0)
  • 2020-12-03 02:49

    The following works:

    <img>
      <xsl:attribute name="src">
        <xsl:value-of select="concat('data:image/gif;base64,',xPath)"/>
      </xsl:attribute>
    </img>
    
    0 讨论(0)
  • 2020-12-03 02:54

    I found this entry from the XSL maiing lists that describes how to use the Saxon extension function xs:base64Binary-to-octet to stream it out to a file using the Java FileOutputStream in an XSLT 2.0 stylesheet:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
    version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema";
    xmlns:saxon="http://saxon.sf.net/";
    xmlns:fos="java.io.FileOutputStream">
    <xsl:template match="/">
       <xsl:variable name="img" select="concat('c:\test\jesper', '.jpg')"/>
       <xsl:variable name="fos" select="fos:new(string($img))"/>
       <xsl:value-of select="fos:write($fos,
    saxon:base64Binary-to-octets(xs:base64Binary(my-base64-encoded-image)))"/>
       <xsl:value-of select="fos:close($fos)"/>
    </xsl:template>
    </xsl:stylesheet>
    
    0 讨论(0)
  • 2020-12-03 02:54

    Transform it to HTML.

    <img src="data:{mime};base64,{data}" />
    
    0 讨论(0)
提交回复
热议问题