Is my impression that this is a problem where a PHP implementation could be better. Who cares if is slow? the result can be cache forever?, is something you will run only once, and the heavyweight work (draw) will be made by C compiled code like the GD library?.
you need speed in stuff that run inside loops (runs N times), or on stuff that delay other stuff (can't be made async), or on stuff that is CPU intensive and runs every time (the computer get angry), or stuff that is very IO intensive (mechanical stuff is slow), or stuff that nees gigawats of memory (the memory gets angry if you touch lots of pages).
stuff that is paralelizable, async, memory light, and not IO intensive don't need any optimization at all. write the better code and have a big smiley :-)