This isn't magic, it's just optipng. I did this locally and got the same file (literally, with the same md5sum):
optipng -o 3 foobar.png
Also, MediaCrush does the same thing transparently+losslessly when you upload a number of files, and it's open source. https://github.com/MediaCrush/MediaCrush