PNG file format manipulation with ColdFusion

All of my recent exploration into how certain image editors handle PNG files made me want to code some CF routines to do some low-level PNG file format manipulation. I have several sites that do PNG generation, and being able to streamline and watermark those files could be a major benefit. It turns out it’s not that hard — I was able to throw something together in the last 24 hours that does all of the following:

  • Read, write, and (somewhat) validate PNG files
  • Remove the unnecessary chunks that I don’t want to stream
  • Add arbitrary text metadata and modification timestamps
  • Optimize the file size a little by consolidating image data (IDAT) chunks

For example:

<cfset fileName="whatever.png">
<cfset png=createObject("component","PNGManip").init(fileName)>
<cfset png.removeChunkTypes("gAMA,tEXt,iTXt,zTXt,iCCP,sRGB,cHRM,pHYs,sPLT,hIST,tIME,oFFs,pCAL,sCAL,gIFg,gIFx,sTER,fRAc,gIFt,mkBF,mkTS,mkBT,prVW,mkBS")>
<cfset png.updateTime()>
<cfset png.consolidateDataChunks()>
<cfset png.appendTextChunk("Rick Osborne","Author")>
<cfset png.writePNG(fileName)>

As a long-term goal, I’d love to add in some color quantization to crush 32-bit PNGs down to 8-bit alpha-indexed PNGs. It seems to be one of those things that is easy to do badly, but tricky to do well.

If you want to see (or use) the code, it’s in SVN at Google Code (PNGmanip.cfc) under an MPL 1.1 license.