The error is very explicit, imagepng expects a resource. To be simple, imagine a resource as an object from which you cant't know the class. In fact, GD is developped in C language, and PHP wraps all unknown C structures inside resources.
So, you need to ask GD to create this resource for you, before using gd-family functions. If you stored your image raw, you'll get it raw and will need to use imagecreatefromstring function.
$gdh = imagecreatefromstring($img);
imagepng($gdh, $cachefile);