I really don't think this can be made to work correctly.  If the passed in buffer is less than the declared size of the image, a bad (or purposefully malicious header) will point this code outside of reasonable bounds.   I don't see any checking to verify the that the passed in len is large enough to accommodate the various structures.