SVG to PNG on the fly with ColdFusion

8 Oct, 2009  |  Written by  |  under ColdFusion

I’ve got a client with a large number of SVG images of products.  The format works really well in a lot of ways, because the images are scalable and look great at any resolution. As usual, Internet Explorer is a thorn in our sides.  Today, it’s because IE doesn’t support PNG. Sheesh.

So I found a great article about converting SVG to PNG with ColdFusion using the Batik Java library. It took a lot of wrangling to finally get it working on the client’s aging ColdFusion 6 server. Here’s a little snippet that essentially caches the converted file and outputs and <img> tag. Works like a champ:

<!— Invoke as <cfmodule template=”/Products/showSVG.cfm” svgFile=”/Assets/SubcategoryGroups/20600.svg” width=”600″> —>
<cfparam name=”attributes.svgFile” type=”string” default=””>
<cfparam name=”attributes.width” type=”string” default=””> <!— You can specify both width & height, just one, or none. —>
<cfparam name=”attributes.height” type=”string” default=””>
<cfparam name=”attributes.alt” type=”string” default=””>

<cfif attributes.svgFile EQ “”>
<!— Do nothing —>
<cfoutput>No SVG file specified</cfoutput>
<!— Make sure the source SVG exists: —>
<cfset svgPath = “#attributes.svgFile#” />
<cfset pngPath = replace(“#svgPath#”, “.svg”, “.png”) />
<cfset svgFile = expandPath(svgPath) />
<cfset pngFile = expandPath(pngPath) />

<cfif FileExists(svgFile)>
<!— Figure out the best way to display this svg. —>

<!— For Firefox and friends, we could output the SVG directly. —>

<!— For IE and many other browsers, we convert to a PNG: —>
<cfif NOT FileExists(pngFile)>
<!— PNG doesn’t exist yet.  Generate it: —>
<cfset t = createObject(“java”, “org.apache.batik.transcoder.image.PNGTranscoder”).init() />
<cfset svgURI = createObject(“java”, “”).init(svgFile).toURL().toString() />
<cfset input = createObject(“java”, “org.apache.batik.transcoder.TranscoderInput”).init(svgURI) />
<cfset ostream = createObject(“java”, “”).init(pngFile) />
<cfset output = createObject(“java”, “org.apache.batik.transcoder.TranscoderOutput”).init(ostream) />
<cfset t.transcode(input, output) />
<cfset ostream.flush() />
<cfset ostream.close() />

<!— <embed src=”#svgPath#” width=”613″ height=”343″ type=”image/svg+xml” /> —>
<img src=”#pngPath#” width=”#attributes.width#” height=”#attributes.height#” alt=”#attributes.alt#” />
<!— SVG doesn’t exist. —>
<cfoutput>File #svgPath# not found.</cfoutput>
<cfcatch type=”any”>
<cfoutput>Error outputting SVG #attributes.svgFile#</cfoutput>

When migrating ColdFusion to a new server, you have to remember to un-install the not-quite-complete Batik library Adobe provides:

  1. Shut down ColdFusion
  2. In Coldfusion9/wwwroot/WEB-INF/cfform/jars/ rename batik*.jar to batik*.jar.disabled
  3. Put a full copy of Batik (24-ish .jar files) in ColdFusion9/wwwroot/WEB-INF/lib
  4. Restart ColdFusion


No Responses so far | Have Your Say!

Leave a Reply